装饰模式,概括的说就是像已有的功能里面添加新的功能,但是确不会对以前的功能造成影响,(符合软件设计的开放-封闭原则)
并且可以根据需要决定何时何地启用哪些功能,以及顺序问题。说到顺序这个问题,其实装饰模式和建造者模式有相似之处,
而建造者模式有顺序之分。以下是具体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,何时不执行。该模式还有一个重要的优点:将类的核心功能和非核心功能分离开,简化类的逻辑。