unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TAbstractString = class protected procedure SetStr(const Value: string); virtual; abstract; function GetStr: string; virtual; abstract; public property Text: string read GetStr write SetStr; end; TString = class(TAbstractString) private FText: string; protected constructor Create(const Value: string); procedure SetStr(const Value: string); override; function GetStr: string; override; end; TStringDecorator = class(TAbstractString) private FString: TString; protected procedure SetStr(const Value: string); override; function GetStr: string; override; public constructor Create(AString: TString); overload; virtual; destructor Destroy; override; end; TUpperCaseString = class(TStringDecorator) protected procedure SetStr(const Value: string); override; function GetStr: string; override; end; TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private FStr: TAbstractString; public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} { TString } constructor TString.Create(const Value: string); begin FText := Value; end; function TString.GetStr: string; begin Result := FText; end; procedure TString.SetStr(const Value: string); begin FText := Value; end; { TStringDecorator } constructor TStringDecorator.Create(AString: TString); begin FString := AString; end; destructor TStringDecorator.Destroy; begin if Assigned(FString) then FString.Free; inherited; end; function TStringDecorator.GetStr: string; begin Result := FString.GetStr; end; procedure TStringDecorator.SetStr(const Value: string); begin FString.SetStr(Value); end; { TUpperCaseString } function TUpperCaseString.GetStr: string; begin Result := UpperCase(FString.GetStr); end; procedure TUpperCaseString.SetStr(const Value: string); begin inherited SetStr(UpperCase(Value)); end; procedure TForm1.FormCreate(Sender: TObject); begin FStr := TUpperCaseString.Create(TString.Create('hello')); end; procedure TForm1.FormDestroy(Sender: TObject); begin FStr.Free; end; procedure TForm1.Button1Click(Sender: TObject); begin Edit1.Text := FStr.Text; end; end.
其中
TAbstractString 等同於 Decorator 結構圖裡面的 Component 類別
TString 等同於 Decorator 結構圖裡面的 ConcreteComponent 類別
TStringDecorator 等同於
Decorator 結構圖裡面的 Decorator 類別
TUpperCaseString 等同於 Decorator 結構圖裡面的
ConcreteDecorator 類別