开发者

Is there a good reason for hiding the leaf object entirely in a composite object, and limiting access to it?

So for example, here is an illustration of how the current code works. I know this may not be a perfect representation of a c开发者_如何学JAVAomposite, 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜