单例模式的实现方法是将构造函数私有,以防止外界通过调用构造函数创建类的对象。
将类的唯一对象保存为静态私有属性,然后提供一个静态公有方法获取该唯一对象,可以保证每次返回的都是同一个对象。
example1:
public class SinglentonInstance {
private SinglentonInstance(){}
private static SinglentonInstance singlenton=new SinglentonInstance();
public static SinglentonInstance getInstance(){
return singlenton;
}
}
example2:
public class SinglentonInstance {
private static SinglentonInstance instance=null;
public static synchronized SinglentonInstance getInstance(){
if(instance==null){
instance=new SinglentonInstance();
}
return instance;
}
}