设计模式之Singleton

设计模式总共有23种模式这仅仅是为了一个目的:解耦+解耦+解耦...(高内聚低耦合知足开闭原则设计模式

介绍:

Singleton模式主要做用是保证在Java应用程序中,一个类Class只有一个实例存在(理解为,居民身份证号具备惟一性)。安全

能够节省内存,由于它限制了实例的个数,有利于Java垃圾回收(garbage collection)。spa

 

模式结构:

1.单例类的构造方法为私有。线程

2.提供一个自身的静态私有成员变量。设计

3.提供一个公有的静态工厂方法。code

实现:

public class Singleton {  
     private static Singleton instance;  
     private Singleton (){
     }   
     public static Singleton getInstance(){    
       if (instance == null){
           synchronized(Singleton.class){
               if (instance == null)
                   instance = new Singleton(); 
           }
       }
       return instance;
     }
     
 }

考虑到线程安全会用到synchronized标识符。咱们知道静态方法是属于类的而不属于对象的。一样的,synchronized修饰的静态方法锁定的是这个类的全部对象。对象

相关文章
相关标签/搜索