In the first example, you’re taking the class instance RequestContext
and inserting into a variable "local" (RequestContext requestContext
) where its maintenance alters the status of the "Singleton" class (from the looks of it).
The second example is (RequestContext.getCurrentInstance().execute(/*coisas*/);
) you would be taking the instance of the class itself and changing it, so if you need it in some local treatment, by doing RequestContext context = RequestContext.getCurrentInstance();
the instance will already be with the .execute()
active.
Observe the codes:
Main Class.java
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 class.java
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 standard because that’s what the Requestcontext class seemed to me to be.
In the first version, you save the instance in the variable
requestContext
. On Monday, if you need her again you’ll need to callgetCurrentInstance
again.– bfavaretto