当前位置:编程学习 > asp >>

设计模式读书笔记-单件模式

单件模式- 确保一个类只有一个实例,全局只有一个入口点。
类如下:
public class Singleton {
       private static Singleton uniqueInstance;
       // other useful instance variables here
      private Singleton() {}
      public static Singleton getInstance() {
              if (uniqueInstance == null) {
                     uniqueInstance = new Singleton();
              }
              return uniqueInstance;
       }
      // other useful methods here
}
采用单件模式,主要解决整个程序中有些资源是共享的,如打印机等。
会发生的问题:解决多线程问题:
解决线程的三种方法:
1 采用同步方法
 Public Static synchronized myClass getInstance()
{
   Retuan new myClass();
};
 但同步一个方法可能造成一个程序效率下降100倍,如果效率不是问题,这样就可以。
否则
2 使用“急切”创建实例
 声明时创建 Private static myClass instance= new myClass();
3 “双重检查加锁“ (JAVA5 以上支持volatile关键字)
public class Singleton {
    private volatile static Singleton uniqueInstance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (uniqueInstance == null) {
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}
所以单价模式是很简单的模式,实际中公用资源常被定义,注意解决多线程问题。
本文出自 “清风” 博客

补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,