简体   繁体   English

使用构图

[英]Using composition

I'm trying to use a custom class to override a method in its super class using composition. 我正在尝试使用自定义类使用合成重写其超类中的方法。 Below is the code im trying, in the class "Bar" what object calls the method doSomethingElse() ? 下面是我正在尝试的代码,在“ Bar”类中,哪个对象调用方法doSomethingElse()? This is not my code and is linked to question - Using composition over inheritance when overriding 这不是我的代码,并且与问题相关联- 覆盖时在继承上使用合成

All of the instantiation is taking place within the child class. 所有实例化都在子类中进行。

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! }
}

you are close, just do this with the Bar class 您很近,只需在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
   }
}

If your original point was to override doSomethingElse, then when using Composition instead, in Bar you would delegate all the other methods (in this case, doSomething) to Foo, and add your overridden behaviour in Bar.doSomethingElse() 如果您的初衷是要覆盖doSomethingElse,则改为使用Composition时,在Bar中,您应将所有其他方法(在本例中为doSomething)委托给Foo,并在Bar.doSomethingElse()中添加覆盖的行为。

So that could be something like: 所以可能是这样的:

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

Also (unrelated to the original question, but I can't help mentioning it) to produce better code, you should inject the Foo dependency, not couple it to Bar. 同样(与原始问题无关,但我不禁提及)以产生更好的代码,您应该注入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! }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM