单例模式在什么情况下用

发布时间:2021-02-26 00:33: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.伸缩性:因为由类自己来控制实例化进程,类就在改变实例化进程上有相应的伸缩性.
以上问题属网友观点,不代表本站立场,仅供参考!