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

设计方式笔记之一 单例模式

2012-07-05 
设计模式笔记之一 单例模式??public class singleton {/** * 预先实例化好了,也可以使用懒实例化,在构造函

设计模式笔记之一 单例模式
    ?
?

public class singleton {/** * 预先实例化好了,也可以使用懒实例化,在构造函数中实例化,不过要注意线程同步的位码头 */private static singleton singleton = new singleton();/** * 私有构造函数 */private singleton() {}/** * 对外接口 * @return */public static singleton getinstance() {return singleton;}}
?
例子2 懒实例化的单例模式
?
/** * 使用懒加载方式 */public class singleton2 {private static singleton2 singleton2 = null;private singleton2() {}/** * 缺点是每次都要判断是否为null,而且同步浪费效率 */public synchronized static singleton2 getinstance() {if (singleton2 == null) {singleton2 = new singleton2();}return singleton2;}}
??
例子3 双重成例检查的单例模式
?
/** * 使用双重成例检查的单例模式 */public class singleton3 {private static singleton3 singleton3 = null;private singleton3() {}/** * 只会判断一次null,效率高了,但是代码稍微复杂了一点 */public static singleton3 getinstance() {if (singleton3 == null) {synchronized (singleton3.class) {if (singleton3 == null) {singleton3 = new singleton3();}}}return singleton3;}}
??
 

热点排行