1

2
{《HeadFirst设计模式》之单例模式 }3
{ 编译工具: Delphi2007 for win32 }4
{ E-Mail : guzh-0417@163.com }5

6
unit uChocolateBoiler;7

8
interface9

10
type11
TChocolateBoiler = class(TObject)12
strict private13
class var14
FUniqueInstance: TChocolateBoiler;15
strict private16
FEmpty : Boolean;17
FBoiled: Boolean;18
constructor Create;19
public20
class function GetInstance: TChocolateBoiler;21
function IsEmpty : Boolean;22
function IsBoiled: Boolean;23
procedure Fill;24
procedure Drain;25
procedure Boil;26
end;27

28
implementation29

30
{ TChocolateBoiler }31

32
procedure TChocolateBoiler.Boil;33
begin34
if (not IsEmpty) and (not IsBoiled) then35
FBoiled := True;36
end;37

38
constructor TChocolateBoiler.Create;39
begin40
FEmpty := True;41
FBoiled := False;42
end;43

44
procedure TChocolateBoiler.Drain;45
begin46
if (not IsEmpty) and IsBoiled then47
FEmpty := True;48
end;49

50
procedure TChocolateBoiler.Fill;51
begin52
if IsEmpty then53
begin54
FEmpty := False;55
FBoiled := False;56
end;57
end;58

59
class function TChocolateBoiler.GetInstance: TChocolateBoiler;60
begin61
if FUniqueInstance = nil then62
begin63
Writeln('Creating unique instance of Chocolate Boiler.');64
FUniqueInstance := TChocolateBoiler.Create;65
end;66

67
Writeln('Returning instance of Chocolate Boiler.');68
Result := FUniqueInstance;69
end;70

71
function TChocolateBoiler.IsBoiled: Boolean;72
begin73
Result := FBoiled;74
end;75

76
function TChocolateBoiler.IsEmpty: Boolean;77
begin78
Result := FEmpty;79
end;80

81
end.1

2
{《HeadFirst设计模式》之单例模式 }3
{ 客户端 }4
{ 编译工具: Delphi2007 for win32 }5
{ E-Mail : guzh-0417@163.com }6

7
program pChocolateBoilerController;8

9
{$APPTYPE CONSOLE}10

11
uses12
SysUtils,13
uChocolateBoiler in 'uChocolateBoiler.pas';14

15
var16
aBoiler : TChocolateBoiler;17
aBoiler2: TChocolateBoiler;18

19
begin20
aBoiler := TChocolateBoiler.GetInstance;21
aBoiler.Fill;22
aBoiler.Boil;23
aBoiler.Drain;24

25
{ will return the existing instance: aBoiler }26
aBoiler2 := TChocolateBoiler.GetInstance;27

28
FreeAndNil(aBoiler);29
{ FreeAndNil(aBoiler2); 同一对象(aBoiler)不能释放两次。}30

31
Readln;32
end.运行结果:
浙公网安备 33010602011771号