- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我们正在为小工具 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 VideocontentMgr();
我的问题是根据接口(interface)隔离原则——应该避免胖/污染接口(interface)。我怎样才能避免污染的方法 - setContent() 在这里。对于通用产品,setContent() 没有用。但是,对于 videocon 产品,它很有用。我怎样才能避免胖/污染方法 setContent()?
最佳答案
For the generic product,
setContent()
is not useful. However, for the videocon product it is useful.
一种解决方案是将成员函数保留在有用的地方 - 仅将其放入 VideocontentMgr
中,并在特定于 VideocontentMgr
子类型的上下文中使用它:
/** if the product is generic **/ ContentMgr *product = new ContentMgr();
/** If the product is videocon **/ {
VideoconContentMgr *vcm = new VideoconContentMgr();
vcm->setContent();
ContentMgr *product = vcm;
}
如果特定于子类的成员函数的有用性超过了初始化时间,请使用 visitor -样的方法。特定于子类的代码仍然绑定(bind)到子类,但现在您添加了一个对通用类不执行任何操作的访问者,并在 VideocontentMgr
类上调用 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);
关于c++ - 如何在这种 C++ 设计场景中避免胖/污染接口(interface) - OOPS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27619273/
我是一名优秀的程序员,十分优秀!