避免一对一关联关系中的样板代码
虽然我用 C++ 编程,但这更多的是关于设计的一般问题。
我注意到,当我的对象处于一对一关联关系时,它们之间往往有很多通用方法,导致样板代码本质上直接调用内部类的方法。
例如,我有一个名为 Tab
的类,它代表一个选项卡及其相应的小部件。我还有一个名为 Tabbable
的类,对象可以继承该类,因此它们可以显示在选项卡中。然后,Tab
可以获取此 Tabbable
对象并正确呈现自身。这两个类都有很多与标题或图标相关的类似方法。
class ITabbable {
public:
ITabbable();
virtual ~ITabbable();
virtual string getTitle() = 0;
virtual widget getContentWidget() = 0;
// etc...
}
class Tab {
public:
Tab(ITabbable* tabbableObject);
// lots of boilerplate code:
string getTitle() {
return m_tabbableObject->getTitle();
}
widget getContentWidget() {
return m_tabbableObject->getContentWidget();
}
// etc...
private:
ITabbable* m_tabbableObject; // association relationship
}
很多代码都是重复的,而且看起来没有必要。继承在这里肯定不起作用,因为你不能在 Tab
中放置 Tab
。
这只是我们必须处理的事情吗?或者有办法解决这些情况吗?
Although I'm programming in C++, this is more of a general question about design.
I noticed that when I have objects in a one-to-one association relationship, there tend to be a lot of common methods between them, leading to boilerplate code that essentially directly calls methods of the inner class.
As an example, I have a class called Tab
that represents a tab and it's corresponding widget. I also have a class called Tabbable
that objects can inherit, so they can be displayed in tabs. A Tab
can then take this Tabbable
object and render itself correctly. Both these classes have a lot of similar methods relating to the title or icon for example.
class ITabbable {
public:
ITabbable();
virtual ~ITabbable();
virtual string getTitle() = 0;
virtual widget getContentWidget() = 0;
// etc...
}
class Tab {
public:
Tab(ITabbable* tabbableObject);
// lots of boilerplate code:
string getTitle() {
return m_tabbableObject->getTitle();
}
widget getContentWidget() {
return m_tabbableObject->getContentWidget();
}
// etc...
private:
ITabbable* m_tabbableObject; // association relationship
}
A lot of code is duplicated and seems unnecessary. Inheritance definitely doesn't work here because you can't put a Tab
in Tab
.
Is this just something we have to deal with? Or are there ways around these situations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
出色地。针对这种特殊情况。为什么不简单地实现
Tab::getTabbable()
呢?像这样:
然后用户可以这样做:
您不必复制所有功能。
更新:此重构通常称为删除中间人。
Well. To this particular situation. Why not simply implement
Tab::getTabbable()
?Like this:
Then users can do:
You don't have to replicate all functionality.
Update: This refactoring is usually called Remove Middle Man.