No singleton, eu sei que eu garanto uma única instancia de uma classe durante toda a vida da minha aplicação.
Entretanto, eu estou precisando passar alguns valores para esse singleton, de modo que esses valores também não morram e possam ser trocados à qualquer hora!
por exemplo:
package testando;
public class Teste {
private static Teste instance;
public static String valor;
public Teste() {
// TODO Auto-generated constructor stub
}
public synchronized static Teste getInstance() {
if(instance==null){
System.out.println("Estou Aqui");
instance = new Teste();
}
return instance;
}
}
Eu preciso que a String valor (não sei se ela vai precisar ser static também), receba um valor em determinado caso, e em outro momento preciso receber de volta este valor que foi fixado… como faço isso???
beleza… eu fiz o get e set… e coloque o valor num servlet e depois tentei recuperar em outro servlet o que eu havia colocado no singleton e não deu certo… mostrou null
package testando;
public class Teste {
private static Teste instance;
public static String valor;
public Teste() {
// TODO Auto-generated constructor stub
}
public synchronized static Teste getInstance() {
if(instance==null){
System.out.println("Estou Aqui");
instance = new Teste();
}
return instance;
}
}
cara, tem que tomar muito cuidado antes de se usar singletons, hj em dia é considerado um antipattern e existem melhores formas de se contornar o problema onde for necessário utilizar um singleton.
O que acontece é que eu preciso ter alguns objetos que vão ficar vivos durante toda a vida da aplicação. É só isso que eu preciso… e o que eu consegui até agora é utilizar o getServletContext().setAttribute(“objeto”, objeto);
[quote=ThiagoWorldCoder]No singleton, eu sei que eu garanto uma única instancia de uma classe durante toda a vida da minha aplicação.
Entretanto, eu estou precisando passar alguns valores para esse singleton, de modo que esses valores também não morram e possam ser trocados à qualquer hora!
por exemplo:
package testando;
public class Teste {
private static Teste instance;
public static String valor;
public Teste() {
// TODO Auto-generated constructor stub
}
public synchronized static Teste getInstance() {
if(instance==null){
System.out.println("Estou Aqui");
instance = new Teste();
}
return instance;
}
}
Eu preciso que a String valor (não sei se ela vai precisar ser static também), receba um valor em determinado caso, e em outro momento preciso receber de volta este valor que foi fixado… como faço isso???
[/quote]
Vc não precisa de um singleton. Vc precisa de um Registry
[code]class Registry {
private static String _valor;
public static void setValor(String valor ){
_valor = valor;
}
public static String getValor(){
return _valor;
[quote=sergiotaborda]Vc não precisa de um singleton. Vc precisa de um Registry
[/quote]
Criar um artefato a mais baseado em um padrão para disponibilizar um objeto na aplicação? Quando ele poderia utilizar os objetos ServletContext (como o autor do post mencionou) ou HttpSession?
[quote=ThiagoWorldCoder]No singleton, eu sei que eu garanto uma única instancia de uma classe durante toda a vida da minha aplicação.
Entretanto, eu estou precisando passar alguns valores para esse singleton, de modo que esses valores também não morram e possam ser trocados à qualquer hora!
valeu![/quote]
First, we create an interface for objects that create instances of the Singleton class. This is essentially a combination of the Abstract Factory, Factory Method and Functor patterns in the GoF book.
[code]/**
An interface defining objects that can create Singleton
instances. /
public interface SingletonFactoryFunctor {
/*
@return An instance of the Singleton.
*/
public Singleton makeInstance();
}
[/code]
Second, we create static wrapper for the Singleton class. Note that by separating the wrapper from the actual implementation, it is possible to both A) provide a well known access point for the Singleton instance and B) allow greater flexiblity as to which subclass to use to create the instance. Note that the wrapper could actually wrap a Singleton interface, rather than a concrete class.
[code]/**
A static container for a single instance of the Singleton
*/
final public class SingletonWrapper {
A reference to the current instance.
*/
static private Singleton _instance = null;
/**
This is the default factory method.
It is called to create a new Singleton when
a new instance is needed and _factory is null.
*/
static private Singleton makeInstance() {
return new Singleton();
}
/**
This is the accessor for the Singleton.
*/
static public synchronized Singleton instance() {
if(null == _instance) {
_instance = (null == _factory) ? makeInstance() : _factory.makeInstance();
}
return _instance;
}
/**
Sets the factory method used to create new instances.
You can set the factory method to null to use the default method.
@param factory The Singleton factory
*/
static public synchronized void setFactory(SingletonFactoryFunctor factory) {
_factory = factory;
}
/**
Sets the current Singleton instance.
You can set this to null to force a new instance to be created the
next time instance() is called.
@param instance The Singleton instance to use.
*/
static public synchronized void setInstance(Singleton instance) {
_instance = instance;
}
}
[/code]
Clients that use this SingletonWrapper need only use something like SingletonWrapper.instance().method().
Note that since SingletonWrapper is final, the instance method can essentially be inlined. Hence the only real over-head here is the check if _instance is null. (Even this could be removed, if we refactor the class to ensure that _instance is never null. For example:
* create a new instance when the class is loaded via a static initializer
* create a new instance when a new factory is assigned via setFactory
* make sure setInstance is never used to change _instance to null, or create a new instance if it is)
This approach allows us to easily alter the specific Singleton instance published–either dynamically or at compile-time–without altering the code that uses the Singleton. Moreover, the Singleton itself need not be aware of the Singleton functionality. Hence this SingletonWrapper can be created for pre-existing classes such as those provided with an API or framework.