Delphi中的Wrapper設計模式

來源:互聯網
上載者:User

Wrapper設計模式能夠把一個類的介面修改成另一個類所需要的介面,然後讓本來因為介面不相容的類能夠在一起配合工作。

在 Delphi中,為了讓兩個類能夠支援同樣的介面,它們必須有同樣的祖先類這樣才能在其他類調用的時候實現多態性。但是有的時候我們希望兩個沒有關係的類 能夠在一起工作,Wrapper設計模式就能夠讓一個類wrap部分另一個類的部分介面(當然也可以是全部,看具體的需要而定),從而能夠類比出一個類似 於“uses”的類的多繼承關係。

讓我們來看一個例子,有一個類TSimple從TObject繼承下來,但是我們希望能把 TSimple這個類放到Delphi的控制項面板(component palette)上,然而我們知道,如果一個類能夠放置到控制項面板上,這個類必須從TComponent派生下來。現在我們不想在改變TSimple的祖 先類TObject的情況下(比如我們並沒有TSimple的原始碼)把TSimple放到控制項面板上,我們可以構建一個繼承自TComponent的 TSimpleWapper類,在TSimpleWapper類中Wrap TSimple的介面。下面是這個例子的範例代碼:

type
 TSample = class (TObject)
private
 FSomeValue: Integer;
public
 function SomeAction(const Data: string): Boolean;
  property SomeValue: Integer read FSomeValue write FSomeValue;
 end;
 TSampleWrapper = class(TComponent)
private
 FSample: TSample;
public
 property Sample: TSample read FSample;
end;

然後我們就可以在TSample類中實現TSample的介面了,代碼如下:

TSampleWrapper = class (TComponent)
private
FSample: TSample;
protected
function GetSomeValue: Integer;
procedure SetSomeValue(Value: Integer);
public
function SomeAction(const Data: string): Boolean;
property Sample: TSample read FSample;
property SomeValue: Integer read GetSomeValue write SetSomeValue;

介面實現代碼如下:

function TSampleWrapper.GetSomeValue: Integer;
begin
Result := Sample.SomeValue;
end;
procedure TSampleWrapper.SetSomeValue(Value: Integer);
begin
Sample.SomeValue := Value;
end;
function TSampleWrapper.SomeAction(const Data: string): Boolean;
begin
Result := Sample.SomeAction(Data);
end;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.