单例模式在什么情况下用

来源:学生作业帮助网 编辑:作业帮 时间:2024/07/28 21:35:30
单例模式在什么情况下用
xTMo@+@BF5 R YɬJH6_ 9ІmZEH!jSh3^:5z3oޛso9{nJNw-W՚U3x!NF*Ưmz'dW[c HNpN 2#}/~5l~)n[=t䝒=/Ű=x8j)C:ɠZJ13(D~6DYjuad1AI&B4GEi8j! gբPY0 3 k!K$5I $&ʘB4tus*r~u 9$0f5RuP6fPH62\YAQY'GdbV4e(M3K ^S ltyDCyHbOf TaQ <\;6&Vl*a1W"SkL'B|x љ'm&Я{/EE~%߾>ԿWy喷`a\<ߴෘwvg҅"C|6SYRKw^Β8Xb8hxͽ Mn˫cw5@CIĭJOhu

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

单例模式在什么情况下用
单例模式:在单例模式中,对活动的单例只有一个实例.对单例类的所有实例化得到的都是相同的一个实例.这个模式也提供一个全局的接口来访问这个类的实例.
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.伸缩性:因为由类自己来控制实例化进程,类就在改变实例化进程上有相应的伸缩性.