首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计方式-单例 Singleton

2012-10-24 
设计模式-单例 Singleton一、构成单例模式要点:①、只有一个实例②、私有的构造方法③、向外界提供访问该实例的公

设计模式-单例 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;
?}
}

热点排行