单例模式(Singleton)

Singleton 

  

  单例模式要求:

 

  1.构造方法为 private ,外部无法通过构建方法构建对象.

 

  2.该类中应该有一个该类的static实例

 

  3.应该有一个 public 的 static 方法,用于提供该实例的引用

 

  4.对于该类的唯一 static 实例有两种方法来初始化.

  

  1).懒汉式单例 

1public class Singleton {
2
3 private static Singleton lazySingleton = null;
4
5 private Singleton() { }
6
7 public static Singleton getInstance() {
8 if(lazySingleton == null)
9 lazySingleton = new Singleton();
10 return lazySingleton;
11 }
12
13}

 

  2).饿汉式单例

1public class Singleton {
2
3 private static final Singleton eagerSingleton = new Singleton();
4
5 private Singleton() { }
6
7 public static Singleton getInstance() {
8 return eagerSingleton;
9
}
10
11}

 

 注意:在多线程环境下,可能会带来问题,多线程环境下最好加锁.而单(多)例模式的应用在连接池中有见到. 

posted on 2010-11-26 13:07  五月十七  阅读(123)  评论(0)    收藏  举报

导航