it's much messy to understand Decorator pattern.
The first intend of this pattern is providing powerful functions rather by inheriting but by composition. I think this key point is under my understable line. The second intend of this pattern is to utlize the power of extension in runtime rather than in compile time.
The second intend is acutally to use the power of the abstract class and to create an instance of a derived class that inherits an abstract class.
so what make my mind messy is that the abstract class, and the compile time versus the runtime.
My question1:
if there are two classes derived from the same abstract class, for example,
public abstract class Beverage
{
public abstract string GetDescription();
}
public abstract class class1:Beverage
{
public override string GetDescription()
{
return "class1";
}
}
public abstract class class2 : Beverage
{
public override string GetDescription()
{
return "class2";
}
}
what does it means when I code like this following
Beverage test=new class1();
test=new class2();
My question2:
when I inherit behavior by subclassing, that behavior is set statically at compile time. In addition, all subclasses must inherit the same behavior. If however, I can extend an object's behavior through composition, then I can do this danamically at runtime.
Whatever, the decorator pattern could add responsibilities to object dynamically which seems very attractive and glory. What'more, to multiply an object's responsiblities is worked by a step-down instance creation.
A gold rule "Open to extension and closed to modifcaiton " is also featured by the decorator pattern
本文深入探讨了装饰器模式的基本概念,包括其提供的功能和运行时扩展能力。通过实例解析,阐述了如何利用抽象类与继承与组合的对比,实现动态扩展对象行为的方法。重点解释了装饰器模式中类之间的关系,以及如何通过动态创建实例来实现行为的增加与替换。
2736

被折叠的 条评论
为什么被折叠?



