01.30 使用抽象類定義接口

使用抽象類定義接口

C.122: Use abstract classes as interfaces when complete separation of interface and implementation is needed

C.122:需要完全隔離接口和實現時使用抽象類作為接口‍

Reason(原因)

Such as on an ABI (link) boundary.

類似ABI邊界的做法。

ABI:https://baike.baidu.com/item/ABI/10912305

Example(示例)

<code>structDevice{
virtual~Device()=default;
virtualvoidwrite(span<constchar>outbuf)=0;
virtualvoidread(span<char>inbuf)=0;
};

classD1:publicDevice{
//...data...
voidwrite(span<constchar>outbuf)override;
voidread(span<char>inbuf)override;
};

classD2:publicDevice{
//...differentdata...
voidwrite(span<constchar>outbuf)override;
voidread(span<char>inbuf)override;
};/<char>/<constchar>/<char>/<constchar>/<char>/<constchar>/<code>

A user can now use D1s and D2s interchangeably through the interface provided by Device. Furthermore, we can update D1 and D2 in ways that are not binary compatible with older versions as long as all access goes through Device.

用戶可以通過Device提供的接口自由地使用D1或D2的對象。除此之外,只要是通過Device訪問,我們甚至可以將D1和D2更新為與舊版本不兼容的二進制形式。

Enforcement(實施建議)

???

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c122-use-abstract-classes-as-interfaces-when-complete-separation-of-interface-and-implementation-is-needed


覺得本文有幫助?請分享給更多人。

更多精彩文章請關注微信公眾號【面向對象思考】!

面向對象開發,面向對象思考!


分享到:


相關文章: