我剛開始學習裝飾器設計模式,不幸的是我不得不通過各種參考來更好地理解裝飾器模式,這導致我非常困惑。所以,據我的理解是擔憂,我相信這是一個裝飾圖案瞭解C裝飾器設計模式#
interface IComponent
{
void Operation();
}
class Component : IComponent
{
public void Operation()
{
Console.WriteLine("I am walking ");
}
}
class DecoratorA : IComponent
{
IComponent component;
public DecoratorA(IComponent c)
{
component = c;
}
public void Operation()
{
component.Operation();
Console.WriteLine("in the rain");
}
}
class DecoratorB : IComponent
{
IComponent component;
public DecoratorB(IComponent c)
{
component = c;
}
public void Operation()
{
component.Operation();
Console.WriteLine("with an umbrella");
}
}
class Client
{
static void Main()
{
IComponent component = new Component();
component.Operation();
DecoratorA decoratorA = new DecoratorA(new Component());
component.Operation();
DecoratorB decoratorB = new DecoratorB(new Component());
component.Operation();
Console.Read();
}
}
,但可以在下面的代碼也是裝飾模式?
class Photo
{
public void Draw()
{
Console.WriteLine("draw a photo");
}
}
class BorderedPhoto : Photo
{
public void drawBorder()
{
Console.WriteLine("draw a border photo");
}
}
class FramePhoto : BorderedPhoto
{
public void frame()
{
Console.WriteLine("frame the photo");
}
}
class Client
{
static void Main()
{
Photo p = new Photo();
p.Draw();
BorderedPhoto b = new BorderedPhoto();
b.Draw();
b.drawBorder();
FramePhoto f = new FramePhoto();
f.Draw();
f.drawBorder();
f.frame();
}
}
我的理解
從我給出的第二個例子中,我們可以調用所有這三種方法,但是從第一個例子,我將無法通過創造讓所有三種方法訪問一個單一的對象。
1 - 裝飾者,2 - 不是。從我的角度來說,裝飾者應該包裝裝飾物:) – tym32167
裝飾者是想延伸的方法吧!!!那爲什麼第二個不是Decorator模式?你能幫我理解嗎? –
@LijinJohn我會說這是因爲一個裝飾器* *裝飾現有的實例。如果我已經有一個'Photo'的實例,我不能簡單地使用'BorderedPhoto'來裝飾它,我不得不創建一個'BorderedPhoto'的實例,然後從我的原始'Photo'實例複製屬性。這不是裝飾。 – Kyle