装饰模式的作用是在已有功能中动态的添加更多的新功能。避免对旧的主类进行修改。简化了主类,并把主类的核心功能和装饰类功能分开。
装饰模式主要应用于:只有在特殊的情况下,才需要执行某些特殊的行为,如下面源码中,可调整装饰的顺序,并添加新的装饰类。
参照了C#的相关源码,整理出Delphi源码,学习之用。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TPerson =class
private
{ Private declarations }
FName:string;
public
{ Public declarations }
Constructor create(AName:string); overload;
procedure Show;virtual;
end;
TFinery = class(TPerson)
protected
FPerson:TPerson;
private
{ Private declarations }
public
{ Public declarations }
procedure Decorate(APerson:TPerson);
procedure Show;override;
end;
TShirts = class(TFinery)
public
{ Public declarations }
procedure Show;override;
end;
TTrouser = class(TFinery)
public
{ Public declarations }
procedure Show;override;
end;
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{TPerson}
Constructor TPerson.create(AName:string);
begin
FName := AName;
inherited Create;
end;
procedure TPerson.Show;
begin
Form1.Memo1.Lines.Add(Format('装扮的%s',[FName]));
end;
{TFinery}
procedure TFinery.Decorate(APerson:TPerson);
begin
FPerson:= APerson;
end;
procedure TFinery.Show;
begin
if Assigned(FPerson) then
FPerson.Show;
end;
{ TShirts}
procedure TShirts.Show;
begin
Form1.Memo1.Lines.Add('大T恤');
inherited Show;
end;
{TTrouser}
procedure TTrouser.Show;
begin
Form1.Memo1.Lines.Add('长裤');
inherited Show;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
vPerson:TPerson;
vTShirt:TShirts;
vTrouser:TTrouser;
begin
vPerson:=TPerson.Create('大大');
vTShirt:=TShirts.Create;
vTrouser:=TTrouser.Create;
vTShirt.Decorate(vPerson);
vTrouser.Decorate(vTShirt);
vTrouser.Show;
end;
end.