Design Pattern----06.Creational.Singleton.Pattern (Delphi Sample)

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

Scheme of Singleton

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.

Scheme of Singleton.

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.

Example of Singleton.

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)

image

unit Pattern;

interface

uses SysUtils;

type
  TSingle = class (Tobject)
  public
    procedure WriteCount;
    class function NewInstance: TObject; override;
    procedure FreeInstance; override;
  end;

implementation

var
  Instance: TObject = nil;
  nCount: Integer = 0;

procedure TSingle.FreeInstance;
begin
  Dec (nCount);
  if nCount = 0 then
  begin
    inherited FreeInstance;
    Instance := nil;
  end;
end;

class function TSingle.NewInstance: TObject;
begin
  if not Assigned (Instance) then
    Instance := inherited NewInstance;
  Result := Instance;
  Inc (nCount);
end;

procedure TSingle.WriteCount;
begin
  WriteLn('Count = ' + IntToStr(nCount));
end;

end.

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

program Creational.Singleton.Pattern;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Pattern in 'Pattern.pas';

var
  s1, s2: TSingle;

begin
//  ReportMemoryLeaksOnShutdown := DebugHook  0;
  try
    s1 := TSingle.Create;
    s2 := TSingle.Create;
    try
      s1.WriteCount;
      s2.WriteCount;

      ReadLn;
    finally
      s1.Free;
      s2.Free;
    end;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.

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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值