我在一次采访中被问到如何在不扩展类的情况下实现动态多态性。如何做到这一点?
最佳答案
Decorator design pattern利用 encapsulation就是你要找的。p>
通过继承实现多态性:
class Cat {
void meow() {
// meow...
}
}
class Lion extends Cat {
}
通过封装实现多态性(装饰器模式):
interface Cat {
void meow();
}
class Lion implements Cat {
private Cat cat;
void meow() {
this.cat.meow();
}
}
ps。有关装饰器的更多信息:http://www.yegor256.com/2015/02/26/composable-decorators.html
关于java - 如何在不扩展类的情况下实现动态多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12347007/