设计模式之Singleton

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

介绍:

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

可以节省内存,因为它限制了实例的个数,有利于Java垃圾回收(garbage collection)。

 

模式结构:

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

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

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

实现:

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修饰的静态方法锁定的是这个类的所有对象。

 

posted on 2016-08-08 12:00  金洪光  阅读(231)  评论(0编辑  收藏  举报

导航