读书人

设计方式-单例 Singleton

发布时间: 2012-10-24 14:15:58 作者: rapoo

设计模式-单例 Singleton

一、构成单例模式要点:

①、只有一个实例

②、私有的构造方法

③、向外界提供访问该实例的公共的静态方法

?

二、分类:

①、饿汉模式

class SingletonOne {

?private SingletonOne() {
?}

?private static SingletonOne st = new SingletonOne();

?public static SingletonOne getST() {
??return st;
?}
}

②、懒汉模式1

class SingletonTwo {
?private SingletonTwo() {
?}

?private static SingletonTwo st = null;

?public synchronized static SingletonTwo getST() {
??if (st == null)
???st = new SingletonTwo();
??return st;
?}
}

③、懒汉模式2

class SingletonThr {
?static class creatSingleton {
??static SingletonThr st = new SingletonThr();
?}

?public static SingletonThr getST() {
??return SingletonThr.creatSingleton.st;
?}
}

读书人网 >软件开发

热点推荐