Intent

  • Ensure a class has only one instance, and provide a global point of access to it.
  • Encapsulated “just-in-time initialization” or “initialization on first use”.

Problem

Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.

Discussion

Make the class of the single instance object responsible for creation, initialization, access, and enforcement. Declare the instance as a private static data member. Provide a public static member function that encapsulates all initialization code, and provides access to the instance.

The client calls the accessor function (using the class name and scope resolution operator) whenever a reference to the single instance is required.

Singleton should be considered only if all three of the following criteria are satisfied:

  • Ownership of the single instance cannot be reasonably assigned
  • Lazy initialization is desirable
  • Global access is not otherwise provided for

If ownership of the single instance, when and how initialization occurs, and global access are not issues, Singleton is not sufficiently interesting.

The Singleton pattern can be extended to support access to an application-specific number of instances.

The “static member function accessor” approach will not support subclassing of the Singleton class. If subclassing is desired, refer to the discussion in the book.

Deleting a Singleton class/instance is a non-trivial design problem. See “To Kill A Singleton” by John Vlissides for a discussion.

Structure

Make the class of the single instance responsible for access and “initialization on first use”. The single instance is a private static attribute. The accessor function is a public static method.

Example

The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, “The President of the United States” is a global point of access that identifies the person in the office.

Check list

  1. Define a private static attribute in the “single instance” class.
  2. Define a public static accessor function in the class.
  3. Do “lazy initialization” (creation on first use) in the accessor function.
  4. Define all constructors to be protected or private.
  5. Clients may only use the accessor function to manipulate the Singleton.

Rules of thumb

  • Abstract Factory, Builder, and Prototype can use Singleton in their implementation.
  • Facade objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.
  • The advantage of Singleton over global variables is that you are absolutely sure of the number of instances when you use Singleton, and, you can change your mind and manage any number of instances.
  • The Singleton design pattern is one of the most inappropriately used patterns. Singletons are intended to be used when a class must have exactly one instance, no more, no less. Designers frequently use Singletons in a misguided attempt to replace global variables. A Singleton is, for intents and purposes, a global variable. The Singleton does not do away with the global; it merely renames it.
  • When is Singleton unnecessary? Short answer: most of the time. Long answer: when it’s simpler to pass an object resource as a reference to the objects that need it, rather than letting objects access the resource globally. The real problem with Singletons is that they give you such a good excuse not to think carefully about the appropriate visibility of an object. Finding the right balance of exposure and protection for an object is critical for maintaining flexibility.
  • Our group had a bad habit of using global data, so I did a study group on Singleton. The next thing I know Singletons appeared everywhere and none of the problems related to global data went away. The answer to the global data question is not, “Make it a Singleton.” The answer is, “Why in the hell are you using global data?” Changing the name doesn’t change the problem. In fact, it may make it worse because it gives you the opportunity to say, “Well I’m not doing that, I’m doing this” – even though this and that are the same thing.

Delphi Sample

UML(Class Diagram)

unit Pattern;interfaceuses SysUtils;typeTSingle = class (Tobject)publicprocedure WriteCount;class function NewInstance: TObject; override;procedure FreeInstance; override;end;implementationvarInstance: TObject = nil;nCount: Integer = 0;procedure TSingle.FreeInstance;
beginDec (nCount);if nCount = 0 thenbegininherited FreeInstance;Instance := nil;end;
end;class function TSingle.NewInstance: TObject;
beginif not Assigned (Instance) thenInstance := inherited NewInstance;Result := Instance;Inc (nCount);
end;procedure TSingle.WriteCount;
beginWriteLn('Count = ' + IntToStr(nCount));
end;end.

------------------------------------------------------------------------------------------------------------------------------

program Creational.Singleton.Pattern;{$APPTYPE CONSOLE}usesSysUtils,Pattern in 'Pattern.pas';vars1, s2: TSingle;begin
//  ReportMemoryLeaksOnShutdown := DebugHook  0;trys1 := TSingle.Create;s2 := TSingle.Create;trys1.WriteCount;s2.WriteCount;ReadLn;finallys1.Free;s2.Free;end;excepton E:Exception doWriteln(E.Classname, ': ', E.Message);end;
end.

转载于:https://www.cnblogs.com/xiuyusoft/archive/2011/06/17/2083829.html

Design Pattern----06.Creational.Singleton.Pattern (Delphi Sample)相关推荐

  1. 设计模式之一:单例模式(Singleton Pattern)

    写这个系列的文章,只为把所学的设计模式再系统的整理一遍.错误和不周到的地方欢迎大家批评.点击这里下载源代码. 什么时候使用单例模式 在程序运行时,某种类型只需要一个实例时,一般采用单例模式.为什么需要 ...

  2. 单件模式(Singleton Pattern)

    单件模式(Singleton Pattern) 概述 Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点.这就提出了一个问题:如何绕过常规的构造器,提供一种机制来保证一个类只 ...

  3. .NET设计模式(2):单件模式(Singleton Pattern)

    转载:http://terrylee.cnblogs.com/archive/2005/12/09/293509.html 单件模式(Singleton Pattern) --.NET设计模式系列之二 ...

  4. 设计模式学习笔记十:单例模式(Singleton Pattern)

    1.概述    单例模式(Singleton Pattern)又称单件模式,单例模式保证一个类仅有一个实例,并提供一个访问的他的全局访问点.通常我们可以让一个全局变量使得一个对象被访问,但它不能防止你 ...

  5. 单件模式(Singleton Pattern)(转自TerryLee)

    概述  Singleton模式要求一个类有且仅有一个实例,并且提供了一个全局的访问点.这就提出了一个问题:如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?客户程序在调用某一个类时,它是不会 ...

  6. C#设计模式之一单例模式(Singleton Pattern)【创建型】

    一.引言 看了李建忠老师的讲的设计模式已经有一段时间了(这段时间大概有一年多了),自己还没有写过自己的.有关设计模式的文章.这次想写一些关于设计模式的文章,用自己的理解和代码来写,算是复习一遍.写作的 ...

  7. 那些年,我们一起写的设计模式(一)——单例模式(Singleton Pattern)

    题记 *度娘上对设计模式(Design pattern)的定义是:"一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结."它由著名的"四人帮",又 ...

  8. Singleton Pattern

    1.单例模式:也叫单件模式,或单态模式.表示创建独一无二的(只有一个实例的)对象. 2.经典单例模式:延迟实例化(适用于非多线程)     /**   * @Class:classical signl ...

  9. Net设计模式实例之单例模式( Singleton Pattern)

    一.单例模式简介(Brief Introduction) 单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点.单例模式因为Singleton封装它的唯 ...

最新文章

  1. 前端人员如何模拟慢网速环境
  2. 第10章 接口、继承与多态----抽象类和接口
  3. Javascript教程:AngularJS的五个超酷特性
  4. AtomicInteger源码分析——基于CAS的乐观锁实现
  5. mysql locate 和 like_MySQL比like语句更高效的写法locate position instr find_in_set
  6. 一定要多角度看事物 | 今日最佳
  7. Installation failed, deleting ./composer.json.安装phpunit报错解决方案
  8. 设计模式(1)-----简单工厂模式
  9. 安装centos7步骤_Centos7下源码编译安装mysql5.7 详细步骤 小白也能安装
  10. Python3 中打的迭代器与生成器
  11. 大数据分析的特点有哪些
  12. RESTful Web Services in Spring 3(上)转载
  13. 计算机网络之万维网WWW
  14. android 内存清理,安卓系统内存清理的方法
  15. 推荐一些逐步深入学习mysql的书籍
  16. 机器人运动学轨迹跟踪控制(Matlab实现)
  17. 把PYTHON文件转换成exe的方法
  18. 最小采样频率计算公式_信号分析基础(五):信号采样与混叠概念
  19. 在CENTOS 7上安装SNIPE-IT进行资产管理
  20. 【AI_数学知识】概率论

热门文章

  1. scala学习笔记-面向对象编程之Trait
  2. 在Windows2016中回到DOS时代用tt练习打字
  3. 两年JAVA程序员的面试总结
  4. 4702: 分糖果系列一
  5. 每个优秀程序员必须具备的技能
  6. python framework jdon_一天学会Python Web框架(十二)产品管理
  7. pip19离线_更新pip为20后不显示下载链接无法离线下载回退pip版本
  8. Xilinx SDK中分配变量的存储地址
  9. CCS初学调试以及RTDX
  10. FPGA加载bit文件可以工作,加载mcs不能工作的原因