你可以这样做,如下所示。
public interface ToyInterface {
public void play();
}
public class Toy implements ToyInterface {
@Override
public void play() {
System.out.println("Play toy");
}
}
public interface BoxInterface {
public void open();
}
public class Box implements BoxInterface {
@Override
public void open() {
System.out.println("open box");
}
}
public class Container implements ToyInterface, BoxInterface {
private BoxInterface box;
private ToyInterface toy;
public Container() {
box = new Box();
toy = new Toy();
}
public BoxInterface getBox() {
return box;
}
public ToyInterface getToy() {
return toy;
}
@Override
public void play() {
System.out.println("play container");
this.toy.play();
}
@Override
public void open() {
System.out.println("open container");
this.box.open();
}
}
然后,您可以访问Container和Box之外的方法。
Container container = new Container();
container.open();
container.getBox().open();
container.play();
container.getToy().play();
你的方式是罚款,因为它可以。 – 2012-08-02 11:05:58
听起来就像组成一样,就像你现在正在做的那样。 – Ushox 2012-08-02 11:10:18
好的,因为没有更好的解决方案,我会用我原来的方法。 – 2012-08-02 13:57:55