What is the difference between these two statements?

1

I was reading some tutorials and documentation and came up with two different ways to declare RequestContext :

RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute(/*coisas*/);

and

RequestContext.getCurrentInstance().execute(/*coisas*/);

What I want to know is if there is any difference between these two, if so, which ones? When should I use each one?

    
asked by anonymous 17.08.2014 / 17:36

1 answer

2

In the first example, you are catching the instance of class RequestContext and inserting into a "local" variable ( RequestContext requestContext ) where its maintenance changes the state of the "Singleton" class (it seems) / p>

Now the second example ( RequestContext.getCurrentInstance().execute(/*coisas*/); ) would be taking the instance of the class itself and changing it, so if you need it in some local processing, doing RequestContext context = RequestContext.getCurrentInstance(); will already have the .execute() active.

Look at the codes:

Main.java class

private static Singleton singleton;

public static void main(String[] args) {

    //Estou alterando a própria classe Singleton;
    Singleton.getSingleton().setAtivo(false);
    System.out.println(Singleton.getSingleton().isAtivo());//Imprime false

    //Aqui a variável singleton está com a instância modificada da classe Singleton;
    singleton = Singleton.getSingleton();
    singleton.setAtivo(true);
    System.out.println(singleton.isAtivo());//Imprime true

    //O que acontece já que a variável singleton e a própria instância Singleton estão compartilhando informação;
    Singleton.getSingleton().setAtivo(false);
    System.out.println(singleton.isAtivo());//Imprime false
    //Ou até:
    singleton.setAtivo(true);
    System.out.println(Singleton.getSingleton().isAtivo());//Imprime true
    //Imprime true pois como a classe Singleton foi instanciada uma única vez (no próprio construtor da classe), as informações acabam compartilhadas; 


}

Singleton.java class

    private boolean ativo;

    private static Singleton retorno = new Singleton();

    private Singleton(){
        this.setAtivo(false);
    }

    public static Singleton getSingleton(){
        return retorno;
    }

    public boolean isAtivo() {
        return ativo;
    }

    public void setAtivo(boolean ativo) {
        this.ativo = ativo;
    }

Note: I used the Singleton pattern because that was what the RequestContext class seemed to be.

    
18.08.2014 / 14:26