如何将抽象工厂与单件模式相结合? [英] How do you combine abstract factory with singleton pattern?
本文介绍了如何将抽象工厂与单件模式相结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在java编码,对这些模式很新。谁能给我一个工厂抽象的例子也使用单例?
I am coding in java and am new with these patterns. Can anyone give me an example of a factory abstract also using singleton?
推荐答案
这是一个实现的类的例子单身模式。此实现也线程安全。它使用双重检查锁定,以便仅在需要时进行同步。
Here's an example of a class implementing the singleton pattern. This implementation is also thread safe. It uses double-checked locking in order to only synchronize when needed.
public class Singleton {
private volatile static Singleton instance; // Note volatile keyword.
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
您可以添加任何(工厂)方法作为成员类 Singleton
。当您获得唯一实例时,这些方法将可用。
You can add any (factory) methods as members of the class Singleton
. These methods will become available when you get the unique instance.
public class Singleton {
/* ... */
/* Singleton implementation */
/* ... */
public MyObject createMyObject() { // Factory method.
return new MyObject();
}
// ...
}
这篇关于如何将抽象工厂与单件模式相结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文