我正在开发一种设计模式,我想确保这里只是Java虚拟机中类的一个实例,通过一个点汇集对某些资源的所有请求,但我不知道这是否可能。
我只能想出一种方法来计算类的实例并在创建第一个实例后销毁所有实例。
这是正确的做法吗?如果没有的话还有其他办法吗?
Use the 单例图案。最简单的实现包括private constructor
and a field
保存其结果,并且static
名称类似于的访问器方法getInstance()
.
私有字段可以从静态初始值设定项块内分配,或者更简单地使用初始值设定项。这getInstance()
方法(必须是公共的)然后简单地返回这个实例,
public class Singleton {
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
请注意,使用“惰性求值”的方法getInstance()
方法(其中
设计模式中提倡的),在Java中没有必要,因为Java已经使用了“lazy
加载中。”你的单例类可能不会被加载,除非它getInstance()
被调用,因此尝试将单例构造推迟到需要时是没有意义的
有了getInstance()
测试单例变量null
并创建单例
那里。
使用此类同样简单:只需获取并保留引用,然后调用其上的方法:
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
一些评论员认为,单例也应该提供公开的最终结果clone()
仅抛出异常的方法,以避免子类“作弊”和clone()
单身人士。然而,很明显,只有一个私有构造函数的类
不能被细分,所以这种偏执似乎没有必要。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)