将叶对象完全隐藏在复合对象中并限制对其的访问是否有充分的理由?
例如,下面是当前代码如何工作的说明。我知道这可能不是复合体的完美表示,但我不确定还能称呼它什么:
public interface MyInterface {
public void doSomething();
public void doSomethingElse();
}
public class MyComposite implements MyInterface {
private MyLeaf myLeaf = new MyLeaf();
public void doSomething() {
// Do something...
}
public void doSomethingElse() {
// Do something else...
myLeaf.doSomethingElse();
}
}
public class MyLeaf implements MyInterface {
public void doSomething() {
// Do something...
}
public void doSomethingElse() {
// Do something else...
}
public void doAnotherSomething() {
// Do another something...
}
}
public class Program {
public static void main(String[] args) {
MyComposite myComposite = new MyComposite();
myComposite.doSomething();
myComposite.doSomethingElse();
// I can't do this right now...
// myComposite.doAnotherSomething();
}
}
我的论点是完全开放对叶对象的访问并仅返回实例,然后调用代码可以用它做任何事。但是,我想知道这样做是否会有缺点。
So for example, here is an illustration of how the current code works. I know this may not be a perfect representation of a composite, but I wasn't sure what else to call it:
public interface MyInterface {
public void doSomething();
public void doSomethingElse();
}
public class MyComposite implements MyInterface {
private MyLeaf myLeaf = new MyLeaf();
public void doSomething() {
// Do something...
}
public void doSomethingElse() {
// Do something else...
myLeaf.doSomethingElse();
}
}
public class MyLeaf implements MyInterface {
public void doSomething() {
// Do something...
}
public void doSomethingElse() {
// Do something else...
}
public void doAnotherSomething() {
// Do another something...
}
}
public class Program {
public static void main(String[] args) {
MyComposite myComposite = new MyComposite();
myComposite.doSomething();
myComposite.doSomethingElse();
// I can't do this right now...
// myComposite.doAnotherSomething();
}
}
My argument is to simply open up access to the leaf object entirely and just return the instance, and then the calling code can do whatever with it. However, I want to know if there would be disadvantages to that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这告诉你你的设计有问题。您的意思是,继承层次结构中较低的方法需要在较高的位置可见。您的接口应该表达可以在实现上执行的所有操作。另外,您的示例可能是 Adapter 而不是 复合。
This is telling you that there's something wrong with your design. What you're saying is that a method lower down in your inheritance hierarchy needs to be visible higher up. Your interface should express all operations that can be performed on implementations. Also, your example might be an Adapter rather than a Composite.