《GOF设计模式》—原型(Prototype)—Delphi源码示例:基于Assign方法的拷贝

说明:

VCL中,TPersistent Assign 方法常用于对象复制。Assign 方法在TPersistent 类中被声明为虚方法,以允许其派生类实现自己的复制操作。如果TPersistent的派生类没有重写Assign 方法,则Assign 方法会调用源对象的AssignTo方法来实现复制操作。

代码:

unit uPrototypeClone;

 

interface

 

uses

    Classes;

 

type

    TBaseObject = class(TPersistent)

    private

        FState: string;

    public

        function Clone: TBaseObject; virtual; abstract;

        //---

        property State: string read FState write FState;

    end;

    TObjectA = class(TBaseObject)

    public

        procedure Assign(Source: TPersistent); override;

        function Clone: TBaseObject; override;

    end;

    TObjectB = class(TBaseObject)

    protected

        procedure AssignTo(Dest: TPersistent); override;

    public

        function Clone: TBaseObject; override;

    end;

 

    TClient = class

    private

        FPrototype: TBaseObject;

    public

        constructor Create(Prototype: TBaseObject);

        destructor Destroy; override;

        //---

        function CreateObject: TBaseObject;

    end;

 

implementation

 

procedure TObjectA.Assign(Source: TPersistent);

begin

    if Source is TObjectA then

    begin

        with Source as TObjectA do

        begin

            self.State := State;

        end;

    end

    else

        inherited;

end;

 

function TObjectA.Clone: TBaseObject;

begin

    Result := TObjectA.Create;

    Result.Assign(self);

end;

 

procedure TObjectB.AssignTo(Dest: TPersistent);

begin

    if Dest is TObjectB then

    begin

        with Dest as TObjectB do

        begin

            State := self.State;

        end;

    end

    else

        inherited;

end;

 

function TObjectB.Clone: TBaseObject;

begin

    Result := TObjectB.Create;

    Result.Assign(self);

end;

 

constructor TClient.Create(Prototype: TBaseObject);

begin

    FPrototype := Prototype;

end;

 

destructor TClient.Destroy;

begin

    FPrototype.Free;

    //---

    inherited;

end;

 

function TClient.CreateObject: TBaseObject;

begin

    Result := FPrototype.Clone;

end;

 

end.

 

procedure TForm1.Button1Click(Sender: TObject);

var

    APrototype,AObject: TBaseObject;

    AClient: TClient;

begin

    APrototype := TObjectB.Create;

    APrototype.State := 'Prototype B';

    //---

    AClient := TClient.Create(APrototype);

    try

        AObject := AClient.CreateObject;

        showmessage(AObject.State);

        AObject.Free;

    finally

        AClient.Free;

    end;

end;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值