Delphi 设计模式:《HeadFirst设计模式》Delphi2007代码---单例模式之ChocolateBoiler[转]
2020-12-13 15:42
标签:des blog http io ar os for sp div Delphi 设计模式:《HeadFirst设计模式》Delphi2007代码---单例模式之ChocolateBoiler[转] 标签:des blog http io ar os for sp div 原文地址:http://www.cnblogs.com/0x2D-0x22/p/4076337.html![]()
1
2
{《HeadFirst设计模式》之单例模式 }
3
{ 编译工具: Delphi2007 for win32 }
4
{ E-Mail : guzh-0417@163.com }
5
6
unit uChocolateBoiler;
7
8
interface
9
10
type
11
TChocolateBoiler = class(TObject)
12
strict private
13
class var
14
FUniqueInstance: TChocolateBoiler;
15
strict private
16
FEmpty : Boolean;
17
FBoiled: Boolean;
18
constructor Create;
19
public
20
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
implementation
29
30
{ TChocolateBoiler }
31
32
procedure TChocolateBoiler.Boil;
33
begin
34
if (not IsEmpty) and (not IsBoiled) then
35
FBoiled := True;
36
end;
37
38
constructor TChocolateBoiler.Create;
39
begin
40
FEmpty := True;
41
FBoiled := False;
42
end;
43
44
procedure TChocolateBoiler.Drain;
45
begin
46
if (not IsEmpty) and IsBoiled then
47
FEmpty := True;
48
end;
49
50
procedure TChocolateBoiler.Fill;
51
begin
52
if IsEmpty then
53
begin
54
FEmpty := False;
55
FBoiled := False;
56
end;
57
end;
58
59
class function TChocolateBoiler.GetInstance: TChocolateBoiler;
60
begin
61
if FUniqueInstance = nil then
62
begin
63
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
begin
73
Result := FBoiled;
74
end;
75
76
function TChocolateBoiler.IsEmpty: Boolean;
77
begin
78
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
uses
12
SysUtils,
13
uChocolateBoiler in ‘uChocolateBoiler.pas‘;
14
15
var
16
aBoiler : TChocolateBoiler;
17
aBoiler2: TChocolateBoiler;
18
19
begin
20
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.
运行结果:
上一篇:win7 32位解决matlba out of memory问题
下一篇:Delphi 设计模式:《HeadFirst设计模式》Delphi7代码---适配器模式之TurkeyAdapter[转]
文章标题:Delphi 设计模式:《HeadFirst设计模式》Delphi2007代码---单例模式之ChocolateBoiler[转]
文章链接:http://soscw.com/index.php/essay/35344.html