1. ChocolateBoiler {《HeadFirst设计模式》之单例模式 } { 编译工具: Delphi2007 for win32 } { E-Mail : xshlife@163.com } unit uChocolateBoiler; interface type TChocolateBoiler = class(TObject) strict private class var FUniqueInstance: TChocolateBoiler; strict private FEmpty : Boolean; FBoiled: Boolean; constructor Create; public class function GetInstance: TChocolateBoiler; function IsEmpty : Boolean; function IsBoiled: Boolean; procedure Fill; procedure Drain; procedure Boil; end; implementation { TChocolateBoiler } procedure TChocolateBoiler.Boil; begin if (not IsEmpty) and (not IsBoiled) then FBoiled := True; end; constructor TChocolateBoiler.Create; begin FEmpty := True; FBoiled := False; end; procedure TChocolateBoiler.Drain; begin if (not IsEmpty) and IsBoiled then FEmpty := True; end; procedure TChocolateBoiler.Fill; begin if IsEmpty then begin FEmpty := False; FBoiled := False; end; end; class function TChocolateBoiler.GetInstance: TChocolateBoiler; begin if FUniqueInstance = nil then begin Writeln('Creating unique instance of Chocolate Boiler.'); FUniqueInstance := TChocolateBoiler.Create; end; Writeln('Returning instance of Chocolate Boiler.'); Result := FUniqueInstance; end; function TChocolateBoiler.IsBoiled: Boolean; begin Result := FBoiled; end; function TChocolateBoiler.IsEmpty: Boolean; begin Result := FEmpty; end; end. 2. 客户端 {《HeadFirst设计模式》之单例模式 } { 客户端 } { 编译工具: Delphi2007 for win32 } { E-Mail : xshlife@163.com } program pChocolateBoilerController; {$APPTYPE CONSOLE} uses SysUtils, uChocolateBoiler in 'uChocolateBoiler.pas'; var aBoiler : TChocolateBoiler; aBoiler2: TChocolateBoiler; begin aBoiler := TChocolateBoiler.GetInstance; aBoiler.Fill; aBoiler.Boil; aBoiler.Drain; { will return the existing instance: aBoiler } aBoiler2 := TChocolateBoiler.GetInstance; FreeAndNil(aBoiler); { FreeAndNil(aBoiler2); 同一对象(aBoiler)不能释放两次。} Readln; end. 运行结果: