posts - 29, comments - 0, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

单例模式

Posted on 2007-05-28 15:47 change 阅读(210) 评论(0)  编辑  收藏

如何使一个类只能够有一个对象 呢,我们知道这样的类的构造函数是必须为私有的,否则用户就可以任意多的生产该类的对象了。那么具体应该怎么实现呢,有两种方式:一种是给类一个该类型的 static 成员对象,每次都调用一个get方法返回该对象,这也就是所谓的饿汉模式;

public class EagerSingleton {
 String name;
 private static final EagerSingleton m_instance = new EagerSingleton();
 
 private EagerSingleton()
 {
  name ="wqh";
 }
 public static EagerSingleton getInstance()
 {
  return m_instance;
 }
 
 public static void main(String[] args) {
  EagerSingleton es ;
  es = EagerSingleton.getInstance();
  System.out.println(es.name);
 }
}

在有一种呢就是在该类型里面先声明一个对象,如何通过一个同步的static方法每次返回同一个 对象,这也就是 所谓的懒汉模式,如下:

public class LazySingleton {
 private static LazySingleton m_instance = null;
 private LazySingleton()
 {
 
 }
 synchronized public  static LazySingleton getInstance()
 {
  if(m_instance == null)
  {
   m_instance = new LazySingleton();
  }
  return m_instance;
 }
 
 public static void main(String[] args) {
  LazySingleton ls;
  ls = LazySingleton.getInstance();
  System.out.println(ls.getClass());
 }
}