使用组合而不是继承的装饰图案 [英] Decorator Pattern Using Composition Instead of Inheritance
问题描述
我以前对装饰器模式的理解是,您使用 WindowDecorator
继承 Window
,然后在重写的方法中,在调用 Window
实现所述方法之前,请先进行一些额外的工作。类似于以下内容:
My previous understanding of the decorator pattern was that you inherit Window
with WindowDecorator
, then in the overridden methods, do some additional work before calling the Window
's implementation of said methods. Similar to the following:
public class Window
{
public virtual void Open()
{
// Open the window
}
}
public class LockableWindow : Window // Decorator
{
public virtual void Open()
{
// Unlock the window
base.Open();
}
}
然而,这实际上是硬编码装饰,那么这样被重构使用组合而不是继承?
However this essentially hardcodes the decoration, so how would this be refactored to use composition instead of inheritance?
推荐答案
对不起,我的C#有点(好吧,非常)生锈,所以有可能是一些语法错误,但基本思想是正确的。
Sorry, my C# is a a bit (OK, very) rusty, so there may be a few syntax errors, but the basic idea is right.
public interface IWindow
{
void Open();
}
public class Window : IWindow
{
public virtual void Open()
{
// Open the window
}
}
public class LockableWindow : IWindow
{
private IWindow _wrappedWindow;
public LockableWindow(IWindow wrappedWindow)
{
_wrappedWindow = wrappedWindow;
}
public virtual void Open()
{
// TODO Unlock window if necessary
_wrappedWindow.open();
}
}
要注意的关键是新的$ $ c> IWindow interface;这就是允许您继续使用多态性。
The key thing to notice is the new IWindow
interface; that's what allows you to keep using polymorphism.
这篇关于使用组合而不是继承的装饰图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!