《GOF设计模式》—桥接(BRIDGE)—Delphi源码示例:创建正确的Implementor对象(参数)

示例:创建正确的Implementor对象(参数)

说明:

如果Abstraction知道所有的ConcreteImplementor类,它就可以在它的构造器中对其中的一个类进行实例化,它可以通过传递给构造器的参数确定实例化哪一个类。

例如,如果一个collection类支持多重实现,就可以根据collection的大小决定实例化哪一个类。链表的实现可以用于较小的collection类,而hash表则可用于较大的collection类。

 

代码:

unit uBridge2;

 

interface

 

uses

    Dialogs;

 

type

    TTable = class;

 

    {抽象类}

    TCollection = class

    private

        FImp: TTable;

    public

        constructor Create(ARecordCount: integer);

        destructor Destroy; override;

        //---

        procedure Operation; virtual;

    end;

    TCollectionA = class(TCollection)

    public

        procedure Operation; override;

    end;

 

    {实现类}

    TTable = class

        procedure OperationImp; virtual; abstract;

    end;

    THash = class(TTable)

        procedure OperationImp; override;

    end;

    TLink = class(TTable)

        procedure OperationImp; override;

    end;

 

implementation

 

constructor TCollection.Create(ARecordCount: integer);

begin

    if ARecordCount < 100 then

        FImp := TLink.Create

    else

        FImp := THash.Create

end;

 

destructor TCollection.Destroy;

begin

    FImp.Free;

    //---

    inherited;

end;

 

procedure TCollection.Operation;

begin

    FImp.OperationImp;

end;

 

procedure THash.OperationImp;

begin

    ShowMessage('Hash');

end;

 

procedure TLink.OperationImp;

begin

    ShowMessage('Link');

end;

 

procedure TCollectionA.Operation;

begin

    inherited;

    //---

    ShowMessage('CollectionA');

end;

 

end.

 

procedure TForm1.Button1Click(Sender: TObject);

var

    ACollection: TCollection;

begin

    ACollection := TCollectionA.Create(200);

    try

        ACollection.Operation;

    finally

        ACollection.Free;

    end;

end;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值