到 Google 资讯主页   
EasyJF首页   资料   源码   软件    论坛   网站    
   使用帮助    
    该信息为本站MyRSS系统缓存内容,部分图片及附件有可能无法正常使用.easyjf.comwww.matrix.org.cn无关,不对该信息负责.通过http://www.matrix.org.cn//resource/article/1/1374.html访问该信息的原始内容.
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   
谈模式(Singleton Pattern)的变形
作者:Jorma 来源:www.matrix.org.cn  发布时间:2006-02-22 17:47:41.717

下面是Singleton Pattern的原意
package Pattern.Creational.Singleton.Demo1;

/**
* <p>Title: THE SINGLETON PATTERN</p>
*
* <p>Description: 建议使用这个方法
* Another approach, suggested by Design Patterns, is to create
* Singletons using a static method to issue and keep track of instances. To
* prevent instantiating the class more than once, we make the constructor
* private so an instance can only be created from within the static method
* of the class.
*
* Other Consequences of the Singleton Pattern
* 1. It can be difficult to subclass a Singleton, since this can only work
* if the base Singleton class has not yet been instantiated.
* 2. You can easily change a Singleton to allow a small number of instances
* where this is allowable and meaningful.
*
* </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author Lin.Xiang.Xiang
* @version 1.0
*/
public class IsSpooler
{
//this is a prototype for a printer-spooler class
//such that only one instance can ever exist
  static boolean instance_flag = false; //true if 1 instance
//the constructor is privatized-
//but need not have any content
  private IsSpooler() {}

//static Instance method returns one instance or null
  static public IsSpooler Instance() {
    if (!instance_flag) {
      instance_flag = true;
      return new IsSpooler(); //only callable from within
    }
    else
      return null; //return no further instances
  }

//-------------------------------------------
  public void finalize() {
    instance_flag = false;
  }

  public static void main(String[] args) {
  }
}



只要稍加修改,我们可控制只创建N个实例,N由我们来定.
下面给出代码示范

  package Pattern.Creational.Singleton.Demo2;

/**
* <p>Title: Singleton Pattern 的变形</p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author Lin.Xiang.Xiang
* @version 1.0
*/
public class N_Instance {
  final static int MAXINSTANCE = 5; //最多只能创建5个实例
  static int instanceCount = 0; //开始无实例

  private N_Instance() {}

  static public N_Instance getInstance() {
    if (instanceCount < MAXINSTANCE) {
      instanceCount++;
      return new N_Instance(); //返回一个实例
    }
    else
      return null; //返回空
  }

  public void finalize() {
    instanceCount--;
  }
}

欢迎交流,指点
QQ:47004223

 
相关文章
 
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   


EasyJF.com 2006 隐私政策 使用EasyJF前必读