Java Singleton Pattern 单例模式
维基百科: 点击打开链接 在应用这个模式时,单例对象的类必须保证只有一个实例存在.
关键点:
1.私有构造函数 - 其他类不能实例化一个新的对象。
2.私有化引用 - 不能进行外部修改。
3.公有静态方法是唯一可以获得对象的方式。
public class SingleObject {
private static SingleObject instance = new SingleObject(); //create an object of SingleObject
private SingleObject(){} //构造函数私有,所以外部无法 new 的方式创建对象
public static SingleObject getInstance(){ //provides a static method to get its static instance to outside world.
return instance;
}
public void showMessage(){
System.out.println("Hello world...");
}
}
public class SingletonPatternDemo {
public static void main(String[] args) {
//SingleObject object = new SingleObject() //非法的构造方法,运行时错误:The constructor SingleObject() is not visible
SingleObject object = SingleObject.getInstance(); Get the only object available
object.showMessage();
}
}
输出结果:Hello world...
更多学习尤其是,多线程环境下的单例模式,请点击:
维基百科:http://zh.wikipedia.org/wiki/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F
http://zz563143188.iteye.com/blog/1847029
参考文献:
http://www.tutorialspoint.com/design_pattern/design_pattern_quick_guide.htm