单例模式在什么情况下用

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/09 18:00:26
单例模式在什么情况下用

单例模式在什么情况下用
单例模式在什么情况下用

单例模式在什么情况下用
单例模式:在单例模式中,对活动的单例只有一个实例.对单例类的所有实例化得到的都是相同的一个实例.这个模式也提供一个全局的接口来访问这个类的实例.
public class Singleton {
//Fields
private static Singleton instance;
//Standard default Constructor
protected Singleton(){};
//Static method for creating the single instance of the Constructor
public static Singleton Instance(){
//initialize if not already done
if(instance == null)
instance = new Singleton();
//return the initialized instance of the Singleton Class
return instance;
}
}public class Client {
public static void main(String []args){
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if(s1 == s2)
System.out.println("The same instance");
}
}单例模式的优点:1.实例控制:单例模式防止其它对象对自己的实例化,确保所有的对象都访问一个实例.
2.伸缩性:因为由类自己来控制实例化进程,类就在改变实例化进程上有相应的伸缩性.