装饰模式与子类 [英] Decorator pattern versus sub classing
问题描述
我可以通过添加子类来解决添加功能的问题,那我为什么要使用装饰器模式?装饰器模式的真正优势是什么?
I can solve the problem of adding functionality by adding sub classing then why should I use decorator pattern what's the real advantage of decorator pattern ?
推荐答案
来自 维基百科的装饰模式
装饰者模式可用于使其有可能扩展(装饰)某个对象的功能在运行时.
The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime.
装饰器模式的全部意义在于动态添加额外的行为/功能,这在设计时当然是不可能的.
The whole point of decorator pattern is to dynamically add additional behaviour/functionality, which is of course not possible at design time.
来自同一篇文章:
装饰者模式是一个子类化的替代方法.子类在编译时添加行为时间,而变化影响到所有原始类的实例;装饰可以提供新的行为单个对象的运行时.
The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.
这篇关于装饰模式与子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!