《GOF设计模式》—装饰(DECORATOR)—Delphi源码示例:装饰接口

示例:装饰接口

说明:

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;

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值