簡體   English   中英

在這種C ++設計方案-OOPS中,如何避免油脂過多/污染的接口?

[英]How to avoid the fat/polluted interface in this scenario of C++ design - OOPS?

我們正在為小工具DTV編寫通用中間件。 我們有一個稱為ContentMgr的模塊,這是一個基類。 現在,針對不同的客戶需求,我們有VideoconContentMgr(例如),它來自ContentMgr。

class ContentMgr
{
  public:

virtual void setContent()
{
  cout<<"Unused function";
}

};

class VideoconContentMgr: public ContentMgr
{
  virtual void setContent()
  {
     cout<<"Do some useful computation;
  }

};

客戶代碼-根據產品類型-

/ **如果產品是通用產品** / ContentMgr * product = new ContentMgr();

/ **如果產品是videocon ** / ContentMgr * product = new VideoconContentMgr();

我的問題是根據接口隔離原理-應該避免油脂過多/污染的接口。 我如何避免受污染的方法-setContent()。 對於通用產品,setContent()無效。 但是,對於videocon產品,它很有用。 如何避免脂肪/污染方法setContent()?

對於通用產品, setContent()無效。 但是,對於videocon產品,它很有用。

一種解決方案是將成員函數保持在有用的位置-僅將其放入VideoconContentMgr ,並在特定於VideoconContentMgr子類型的上下文中使用它:

/** if the product is generic **/ ContentMgr *product = new ContentMgr();

/** If the product is videocon **/ {
    VideoconContentMgr *vcm = new VideoconContentMgr();
    vcm->setContent();
    ContentMgr *product = vcm;
}

如果特定於子類的成員函數的有用性超出了初始化時間,請使用類似訪問者的方法。 特定於子類的代碼仍然綁定到子類,但是現在您添加了對通用類不執行任何操作的訪問者,並在VideoconContentMgr類上調用setContent()

struct ContentMgrVisitor {
  virtual void visitGeneric(ContentMgr& m) {};
  virtual void visitVideo(VideoconContentMgr& vm) {};
};

struct ContentMgr
{
  virtual void accept(ContentMgrVisitor& v)
  {
    v.visitGeneric(this);
  }
};

struct VideoconContentMgr: public ContentMgr
{
  virtual void setContent()
  {
     cout<<"Do some useful computation;
  }
  virtual void accept(ContentMgrVisitor& v)
  {
     v.visitVideo(this);
  }
};

現在,想要致電setContent的客戶可以從訪問者處進行操作:

class SetContentVisitor : public ContentMgrVisitor {
    void visitVideo(VideoconContentMgr& vm) {
        vm.setContent();
    }
};
...
ContentMgr *mgr = ... // Comes from somewhere
SetContentVisitor scv;
mgr->accept(scv);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM