示例:装饰接口
说明:
(1)、定义
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
(2)、结构
组件:
Component:组件。定义一个对象接口,可以给这些对象动态地添加职责。
ConcreteComponent:具体组件。定义一个对象,可以给这个对象添加一些职责。
装饰组件:
Decorator:装饰组件。维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。
ConcreteDecorator:具体装饰组件。向组件添加职责。
协作:
Decorator将请求转发给它的Component对象,并有可能在转发请求前后执行一些附加的动作。
代码:
unit uDecortor;
interface
uses Dialogs;
type
TComponent = class
public
procedure Operation; virtual; abstract;
end;
TConcreteComponent = class(TComponent)
public
procedure Operation; override;
end;
TDecorator = class(TComponent)
private
FComponent: TComponent;
public
constructor Create(const AComponent: TComponent);
destructor Destroy; override;
//---
procedure Operation; override;
end;
TConcreteDecoratorA = class(TDecorator)
private
FAddedState: string;
public
constructor Create(const AComponent: TComponent; const AAddedState: string);
//---
procedure Operation; override;
end;
TConcreteDecoratorB = class(TDecorator)
private
procedure AddedBehavior;
public
procedure Operation; override;
end;
implementation
constructor TDecorator.Create(const AComponent: TComponent);
begin
inherited Create;
//---
FComponent := AComponent;
end;
destructor TDecorator.Destroy;
begin
if Assigned(FComponent) then
FComponent.Free;
//---
inherited;
end;
procedure TDecorator.Operation;
begin
FComponent.Operation;
end;
procedure TConcreteComponent.Operation;
begin
ShowMessage('ConcreteComponent');
end;
constructor TConcreteDecoratorA.Create(const AComponent: TComponent;
const AAddedState: string);
begin
inherited Create(AComponent);
//---
FAddedState := AAddedState;
end;
procedure TConcreteDecoratorA.Operation;
begin
inherited;
//---
ShowMessage(FAddedState);
end;
procedure TConcreteDecoratorB.AddedBehavior;
begin
ShowMessage('AddedBehavior');
end;
procedure TConcreteDecoratorB.Operation;
begin
inherited;
//---
AddedBehavior;
end;
end.
procedure TForm1.Button1Click(Sender: TObject);
var
AComponent: TComponent;
begin
AComponent := TConcreteDecoratorA.Create(TConcreteDecoratorB.Create(TConcreteComponent.Create), '123');
AComponent.Operation;
AComponent.Free;
end;