超越时使用组合继承 [英] Using composition over inheritance when overriding
本文介绍了超越时使用组合继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
是的,您可以使用委派。 Bar
包含一个 Foo $ c,而不是从
Foo
$ c>并代表它选择它。
interface SomeMethods {
void doSomething();
void doSomethingElse();
}
class Foo实现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(){//做别的事情! }
}
If I have a class that I would like to customise by overriding one if its methods the only I can do this is by using inheritance (sub-classing and overriding method) ? Is it possible to use composition in some way to achieve same goal ?
解决方案
Yes, you can use delegation. Instead of deriving from Foo
in the example below, Bar
contains a Foo
and delegates to it where it chooses.
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! }
}
这篇关于超越时使用组合继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文