大话设计模式之-----装饰模式

来源:互联网 发布:135端口入侵教程 编辑:程序博客网 时间:2024/05/31 13:14

program Decorate;{$APPTYPE CONSOLE}uses  SysUtils;type  TPerons = class  private    name: string;  public    constructor Create(AName: string); overload;    constructor Create(); overload;    procedure Show(); virtual;  end;  Tfinery = class(TPerons)  protected    component: TPerons;  public    procedure Decorate(AComponent: TPerons);    procedure Show(); override;  end;  TShirts = class(Tfinery)  public    procedure Show(); override;  end;  TBigtrouser = class(Tfinery)  public    procedure Show(); override;  end;    THat = class(Tfinery)  public    procedure Show(); override;  end;{ TPerons }constructor TPerons.Create(AName: string);begin  name := aname;end;constructor TPerons.Create;beginend;procedure TPerons.Show;begin  Writeln('装扮的' + name);end;{ Tfinery }procedure Tfinery.Decorate(AComponent: TPerons);begin  component := acomponent;end;procedure Tfinery.Show;begin  if component <> nil then    component.Show;end;{ TShirts }procedure TShirts.Show;begin  Writeln('TShirts');  inherited;  end;{ TBigtrouser }procedure TBigtrouser.Show;begin  Writeln('TBigtrouser');  inherited;end;{ THat }procedure THat.Show;begin  Writeln('THat');  inherited;end;var  xc: TPerons;  sh: TShirts;  bi: TBigtrouser;  hat: THat;begin  try    { TODO -oUser -cConsole Main : Insert code here }    xc := TPerons.Create('小菜');    sh := TShirts.Create();    bi := TBigtrouser.Create();    hat:= THat.Create();    bi.Decorate(xc);    sh.Decorate(bi);    hat.Decorate(sh);    hat.Show;    xc.Free;    sh.Free;    bi.Free;    hat.Free;  except    on E: Exception do      Writeln(E.ClassName, ': ', E.Message);  end;end.


新的扩展类通过包含原有的类然后调用虚函数进行扩展功能的实现。

 

装饰模式:

  装饰模式可以使类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。从而可以不影响类核心的情况下添加功能。

原创粉丝点击