创建型设计模式 单例模式

创建型 单例模式
场景

  • 当类只能有一个实例而且用户可以从一个众所周知的访问点访问它时
  • 当类可通过子类化来进行扩展,且系统中只能存在所有子类中的一个时


角色
SingletonClass  允许用户类访问它的唯一实例  
协作
用户类只能通过单例类(SingletonClass)公开的静态成员函数来获取单例类的唯一实例

特点

  • 确保了实例的唯一性
  • 方便的修改类的实例化过程
  • 每次对象请求引用时都要检查是否存在类的实例,这造成一定的开销


实现

public class Singleton {
    private static Singleton theSingleton;
    public static Singleton getInstance(){
     if(theSingleton==null){
         theSingleton = new Singleton();
     }
     return theSingleton
    }
    // other code ....
}


 

发布了231 篇原创文章 · 获赞 3 · 访问量 7987

猜你喜欢

转载自blog.csdn.net/qq_32265719/article/details/103905160