《GOF设计模式》—原型(Prototype)—Delphi源码示例:原型接口

来源:互联网 发布:印度药品 知乎 编辑:程序博客网 时间:2024/05/21 20:24


示例:原型接口

说明:

1)、定义

用原型实例指定要创建对象的种类,并且通过拷贝这些原型实例创建新的同类对象。

2)、结构

原型

Prototype:抽象原型,声明一个克隆自身的接口。

ConcretePrototype:具体原型,实现一个克隆自身的操作。

客户端

Client:让一个原型克隆自身从而创建一个新的对象。

代码:

unit uPrototype;

 

interface

 

type

   TPrototype = class

   private

       FState: string;

   public

       function Clone: TPrototype; virtual; abstract;

       //---

       property State: string read FState write FState;

   end;

   TConcretePrototype1 = class(TPrototype)

   private

       function Copy: TConcretePrototype1;

   public

       function Clone: TPrototype; override;

   end;

   TConcretePrototype2 = class(TPrototype)

   private

       function Copy: TConcretePrototype2;

   public

       function Clone: TPrototype; override;

   end;

 

   TClient = class

   private

       FPrototype: TPrototype;

   public

       constructor Create(Prototype: TPrototype);

       destructor Destroy; override;

       //---

       function Opteration: TPrototype;

   end;

 

implementation

 

function TConcretePrototype1.Clone: TPrototype;

begin

   Result := self.Copy;

end;

 

function TConcretePrototype1.Copy: TConcretePrototype1;

begin

   Result := TConcretePrototype1.Create;

   Result.State := self.State;

end;

 

function TConcretePrototype2.Clone: TPrototype;

begin

   Result := self.Copy;

end;

 

function TConcretePrototype2.Copy: TConcretePrototype2;

begin

   Result := TConcretePrototype2.Create;

   Result.State := self.State;

end;

 

constructor TClient.Create(Prototype: TPrototype);

begin

   FPrototype := Prototype;

end;

 

destructor TClient.Destroy;

begin

   FPrototype.Free;

   //---

   inherited;

end;

 

function TClient.Opteration: TPrototype;

var

   p: TPrototype;

begin

   p := FPrototype.Clone;

   Result := p;

end;

 

end.

 

procedure TForm1.Button3Click(Sender: TObject);

var

   Prototype1: TPrototype;

   Client:TClient;

   AItem: TPrototype;

begin

   {Prototype1 := TConcretePrototype1.Create;

   Prototype1.State := 'Prototype1'; }

   //---

   Prototype1 := TConcretePrototype2.Create;

   Prototype1.State := 'Prototype2';

   //---

   Client := TClient.Create(Prototype1);

   try

       AItem := Client.Opteration;

       showmessage(AItem.State);

       AItem.Free;

   finally

       Client.Free;

   end;

end;

0 0
原创粉丝点击