封装和对象指针
class CommandSchedule
{
private :
List<SubSchedule*> mSubScheduleList;
public :
void addSubSchedule (int id)
{
mSubScheduleList.add(new SubSchedule(id));
}
SubSchedule* addSubSchedule (int id)
{
SubSchedule* item = new SubSchedule(id);
mSubScheduleList.add(item);
return item;
}
};
在此类中,我定义了 2 个 addSubSchedule 函数,一个返回 void,一个返回指向对象的指针。
所以,我的问题是,返回指向对象的指针的函数是否破坏了 CommandSchedule 类的封装?我对封装问题感到不舒服,因此非常感谢任何帮助。
class CommandSchedule
{
private :
List<SubSchedule*> mSubScheduleList;
public :
void addSubSchedule (int id)
{
mSubScheduleList.add(new SubSchedule(id));
}
SubSchedule* addSubSchedule (int id)
{
SubSchedule* item = new SubSchedule(id);
mSubScheduleList.add(item);
return item;
}
};
In this class, I define 2 addSubSchedule functions one returning void, one returning pointer to the object.
So, my question is that, if the function, which returning pointer to the object, breaks the encapsulation of CommandSchedule class ? I feel uncomfortable with encapsulation issue, so any help is appreciated a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么它会破坏封装?对象的内部表示仍然是隐藏的:
除非
SubSchedule
也被视为内部表示,否则这里没有问题。在封装良好的类中,只有其成员函数可以操作其内部细节。在本例中,使用
List
的事实似乎是一个细节,因为公共接口的用户所关心的只是该类允许他添加子计划。如何存储这些子计划是内部细节。您稍后可以更改此详细信息(例如,将它们存储在SortedList
中),而不会影响公共界面的用户。因此,将List<...>
变量设置为私有可以促进良好的封装。如果界面的用户希望能够直接操作
SubSchedule
对象,那么公开它就没有问题。但如果没有理由这样做,那么 SubSchedule 的使用也可能是一个内部细节,因此不应在公共接口中公开。Why would it break encapsulation? The internal representation of your objects is still hidden:
Unless
SubSchedule
is also considered internal representation, there's no problem here.In a well-encapsulated class only its member functions can manipulate its internal details. In this case, the fact that a
List
is used seems to be a detail, because all that an user of the public interface cares about is that the class lets him add subschedules. How those subschedules are stored is an internal detail. You could later change this detail (say, storing them in aSortedList
instead) without affecting the users of the public interface. So, making theList<...>
variable private promotes good encapsulation.If the user of the interface expects to be able to manipulate
SubSchedule
objects directly, then there's no problem in exposing that. But if there's no reason to do that, then the use ofSubSchedule
s is probably an internal detail as well, and as such should not be exposed in the public interface.