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

本文介绍了一个使用桥接设计模式的示例,展示了如何通过选择不同的实现来改变对象的行为。当集合大小超过阈值时,会从链表实现切换到哈希表实现,以提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

示例:创建正确的Implementor对象(缺省的实现)

说明:

创建正确Implementor对象的另外一种方法是首先选择一个缺省的实现,然后根据需要改变这个实现。

例如,如果一个collection的大小超出了一定的阈值时,它将会切换它的实现,使之更适用于表目较多的collection

 

代码:

 

unit uBridge3;

 

interface

 

uses

    Dialogs;

 

type

    TTable = class;

 

    {抽象类}

    TCollection = class

    private

        FImp: TTable;

        FCount: integer;

        procedure SetCount(const Value: integer);

    public

        constructor Create;

        destructor Destroy; override;

        //---

        procedure Operation; virtual;

        property Count: integer read FCount write SetCount;

    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;

begin

    FImp := TLink.Create;

end;

 

destructor TCollection.Destroy;

begin

    FImp.Free;

    //---

    inherited;

end;

 

procedure TCollection.Operation;

begin

    FImp.OperationImp;

end;

 

procedure TCollection.SetCount(const Value: integer);

begin

    if FCount <> Value then

    begin

        FCount := Value;

        //---

        FImp.Free;

        if FCount < 100 then

            FImp := TLink.Create

        else

            FImp := THash.Create;

    end;

end;

 

procedure THash.OperationImp;

begin

    ShowMessage('Hash');

end;

 

procedure TLink.OperationImp;

begin

    ShowMessage('Link');

end;

 

procedure TCollectionA.Operation;

begin

    inherited;

end;

 

end.

 

procedure TForm1.Button1Click(Sender: TObject);

var

    ACollection: TCollection;

begin

    ACollection := TCollectionA.Create;

    try

        ACollection.Operation;

        //---

        ACollection.Count := 200;

        ACollection.Operation;

    finally

        ACollection.Free;

    end;

end;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值