使用构图

时间:2011-09-28 15:25:26

标签: java design-patterns

我正在尝试使用自定义类来使用合成覆盖其超类中的方法。 下面是我尝试的代码,在类“Bar”中什么对象调用方法doSomethingElse()?这不是我的代码,而是与问题相关联 - Using composition over inheritance when overriding

所有实例化都在子类中进行。

class Child extents Parent(){

public Child(){
   super();
   addButtons():
}
 addButtons(){
   <custom code here>
}

}


class Parent(){
 addButtons(){
   add(button1);
}
}

interface SomeMethods {
  void doSomething();
  void doSomethingElse();
}

class Foo implements SomeMethod {
  public void doSomething() { // implementation }
  public void doSomethingElse() { // implementation }
}

class Bar implements SomeMethod {
   private final Foo foo = new Foo();

   public void doSomething() { foo.doSomething(); }
   public void doSomethingElse() { // do something else! }
}

2 个答案:

答案 0 :(得分:1)

你很接近,只需使用Bar类

class Bar extends Foo {
   // note Bar is still of type SomeMethods because it extends a class of that type.
   public void doSomething() {
      super.doSomething();
      //add more code here if you want to do some more stuff, note you don't need to define this function if you don't need to do anything else.
   }
   public void doSomethingElse() {
      //don't call super, and do whatever you like
   }
}

答案 1 :(得分:0)

如果您的原始点是覆盖doSomethingElse,那么在使用Composition时,在Bar中您将所有其他方法(在本例中为doSomething)委托给Foo,并在Bar.doSomethingElse()中添加重写行为

这可能是这样的:

public void doSomethingElse() {
    .... // custom stuff
    foo.doSomethingElse(); // this is the equivalent of an inheritance super call, so it's optional
    .... // other custom stuff
}

另外(与原始问题无关,但我不禁提及它)生成更好的代码,你应该注入Foo依赖,而不是将它耦合到Bar。

class Bar implements SomeMethod {
   private final SomeMethod foo;

   public Bar(SomeMethod foo) {
     this.foo = foo;  
   }

   public void doSomething() { foo.doSomething(); }
   public void doSomethingElse() { // do something else! }
}
相关问题