Head First Design Patterns 阅读笔记之五: Singleton Pattern

为什么需要 Singleton Pattern

一般来说,我们需要某个对象时,就使用 new 操作。在管理资源池的情况下,比如连接控制器或者线程池或者登记信息,需要保证在任何时候只有一个实例,这就需要 Singleton Pattern。Sinleton Pattern 的核心在于没有 public constructor。


如何使用 Singleton Pattern

一个例子:

public class Singleton
{
    private static Singleton uniqueInstance;

    // other useful instance variables here

    private Singleton {}

    public static Singleton getInstance()
    {
        if(uniqueInstace == null) uniqueInstance = new Singleton();
        return uniqueInstace;
    }

    // other useful methods here
}

有了 Singleton Pattern 的经典实现,现在看下定义:

The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

主要说明两点:

  • We are taking a class and letting it manage a single instace of itself. We’re also preventing any other class form creating a new instance on its own. To get an instance, you have got to go through the class itself.
  • We are also providing a global access point to the instance: whenever you need an instance, just query the class and it will hand you back the single instance. As you have seen, we can implement this so that the Singleton is created in a lazy manner, which is especially important for resources intensive objects.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值