什么是单态模式,其实很简单,就是让一个对象只能生成一个实例.Singleton的目的就是控制对象的产生.Singleton一般应用在资源访问,数据库连接等只需(能)有一个实例的地方.单态模式的设计就是完成一个对象是否存在并且是否需要创建的问题:
实例:
/**
* yangxh_520@yahoo.com.cn
* @author mymy5
* 2007.09.18
*/
//设计模式的构造有好几种方式它们有各自的优缺点
(1)第一种形式,此种方法使用了static 需要放弃同步
package cn.yxh.shejimoshi.singleton;
public class MySingleton {
public void printTxt(){
System.out.println("单态模式1");
}
private static MySingleton _instance = new MySingleton(); //注意为private仅供内部调用
private MySingleton(){//构造对象
}
public static MySingleton getInstance(){
return _instance;
}
}
(2)第二种形式,使用同步关键字synchronized
使用synchronized 如果是多个线程,会消耗很大内存,并且有可能造成瓶颈
package cn.yxh.shejimoshi.singleton;
public class MySingleton2 {
private static MySingleton2 _instance;
public void printTxt(){
System.out.println("单态模式2");
}
public static synchronized MySingleton2 getInstance(){
if(_instance==null){
_instance = new MySingleton2();
}
return _instance;
}
}
(3)使用比较多人用的Double-checked locking
package cn.yxh.shejimoshi.singleton;
public class MySingleton3 {
private static MySingleton3 _instance;
public void printTxt(){
System.out.println("单态模式3");
}
public static MySingleton3 getInstance(){
if(_instance==null){
synchronized(MySingleton3.class){
if(_instance==null){
_instance = new MySingleton3();
}
}
}
return _instance;
}
}