设计模式之Singleton(单态模式)

源地址:我的技术博客http://linger.devhub.com/blog/700994-singleton/

设计模式之Singleton(单态模式)

      所谓的单态模式,即表示一个类只有一个实例。很多时候我们只需要实例化一个对象,比如做界面时,点击一个button会弹出一个对话框,如果不是单态模式,万一由于响应比较慢导致用户点击了很多次,结果不是弹出很多对话框,这时如果对话框是单态模式就不同了。(关于singleton的好处《大话设计模式》中有这么一段话,)。

     Singleton的实现方法有两种,都是利用静态变量实现的,当然singleton实现的前提是构造函数是私有的。

方法一是lazy instantiation,当需要用到实例时才实例化:

public static Singleton instance() {

       if(uniqueInstance == null) uniqueInstance = new Singleton();

       return uniqueInstance;

     }

当然上面的实现有个问题,就是在多线程下,有可能会实例化不止一个对象。最好就用到线程同步,具体百度百科有(http://baike.baidu.com/view/1035727.htm)。不过用到线程同步必然会导致浪费资源。

     方法二是eager instantiation:

private static Singleton uniqueInstance = new Singleton();

public static Singleton instance() {

       return uniqueInstance;

     }

.net中这么解释的,在类被加载时就实例化了。

 

     还有一个值得注意的问题,就是当该类有子类时,子类也需要单态模式,怎么处理,也是有两种方法。

     方法一,在父类添加一个返回子类实例的函数:

public static MazeFactory instance() {

       if (uniqueInstance == null) return instance("enchanted");

       else return uniqueInstance;

     }

     // Create the instance using the specified String name.

     public static MazeFactory instance(String name) {

       if(uniqueInstance == null)

         if (name.equals("enchanted"))

           uniqueInstance = new EnchantedMazeFactory();

         else if (name.equals("agent"))

           uniqueInstance = new AgentMazeFactory();

       return uniqueInstance;

     }

     方法二,在各子类中添加自己的返回实例的函数:

public class EnchantedMazeFactory extends MazeFactory {

     // Return a reference to the single instance.

     public static MazeFactory instance() {

       if(uniqueInstance == null)

         uniqueInstance = new EnchantedMazeFactory();

       return uniqueInstance;

     }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值