永发信息网

单例模式怎么实现,单例模式在什么情况下用

答案:1  悬赏:0  手机版
解决时间 2021-05-17 23:54
  • 提问者网友:自食苦果
  • 2021-05-17 17:21
单例模式怎么实现,单例模式在什么情况下用
最佳答案
  • 五星知识达人网友:往事隔山水
  • 2021-05-17 17:48
单例模式:在单例模式中,对活动的单例只有一个实例。对单例类的所有实例化得到的都是相同的一个实例。这个模式也提供一个全局的接口来访问这个类的实例。
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。伸缩性:因为由类自己来控制实例化进程,类就在改变实例化进程上有相应的伸缩性。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯