Delphi装饰模式

装饰模式,概括的说就是像已有的功能里面添加新的功能,但是确不会对以前的功能造成影响,(符合软件设计的开放-封闭原则)

并且可以根据需要决定何时何地启用哪些功能,以及顺序问题。说到顺序这个问题,其实装饰模式和建造者模式有相似之处,

而建造者模式有顺序之分。以下是具体Demo。

//模式单元

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  ICloseComponent = interface
     procedure Operation;
  end;

  TconcreteComponent = class(TInterfacedObject,ICloseComponent)
  public
    procedure Operation;
  end;

  TDecorator = class(TInterfacedObject,ICloseComponent)
  public
    FComponent : ICloseComponent;
    procedure SetComponent(AComponent : ICloseComponent);
    procedure Operation;virtual;
  end;

  TConDecoratorA=class(TDecorator)
     procedure Operation;override;
  end;

  TConDecoratorB=class(TDecorator)
     procedure Operation;override;
  end;


implementation
   uses uMyCommon;
{ TconcreteComponent }

procedure TconcreteComponent.Operation;
begin
  Writelog('以下是具体步骤');
end;

procedure TDecorator.SetComponent(AComponent: ICloseComponent);
begin
  FComponent := AComponent;
end;

procedure TDecorator.Operation;
begin
  FComponent.Operation;
end;

procedure TConDecoratorA.Operation;
begin
  inherited;
  Writelog('A类型操作');
end;

{ TConDecoratorB }

procedure TConDecoratorB.Operation;
begin
  inherited;
  Writelog('B类型操作');
end;

end.

//调用代码

procedure TForm1.Button1Click(Sender: TObject);
var
  c: TconcreteComponent;
  d1,d2 : TDecorator;

begin
  c := TconcreteComponent.Create;
  d1 := TConDecoratorA.Create;
  d2 := TConDecoratorB.Create;
  d1.SetComponent(c);
  d2.SetComponent(d1);
  d2.Operation;
end;

//执行结果是:c和A和B的Operation都执行了,其中C建议完成初始化之类的工作

我们可以将A视为最开始的一个功能,在加入B的同时,不会影响A。如果哪一天还需要增加C操作,给C建一个类,

然后在调用的时候加上去就好了,同样对A和B毫不影响,甚至可以根据需要调换BC的顺序,也可以根据需要,

决定何时执行C,何时不执行。该模式还有一个重要的优点:将类的核心功能和非核心功能分离开,简化类的逻辑。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值