本文主要是介绍《GOF设计模式》—原型(Prototype)—Delphi源码示例:原型接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
示例:原型接口
说明:
(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;
这篇关于《GOF设计模式》—原型(Prototype)—Delphi源码示例:原型接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!