如何通过装饰设计模式扩展密封类?

时间:2013-11-23 07:59:24

标签: c# oop design-patterns

装饰者模式用法:

任何人都可以通过Decor模式展示如何扩展密封类功能的示例。

1 个答案:

答案 0 :(得分:2)

无法从.NET继承sealed class。所以,如果你想创建继承密封类的装饰器,那么回答是 - 它是不可能的。

public class Decorator : SealedClass // not possible

如果您的密封类实现了某个接口或继承了一些基类,那么您可以创建继承相同类/接口的装饰器。装饰师看起来不像你的班级客户,但你可以用它来装饰你的班级。

public sealed class SealedClass : InterfaceA

public class Decorator : InterfaceA

另一种选择 - 创建一个新的界面(它看起来就像你的密封类接口)并为这个界面实现装饰器。然后为此接口创建密封类适配器。客户端将使用您的新界面。您将能够装饰适配器

public class Decorator : InterfaceB // same members as SealedClass have

public class Adapter : InterfaceB
{
    private SealedClass adaptee;

    public Adapter(SealedClasss adaptee)
    {
       this.adaptee = adaptee;
    }

    public int Member1()
    {
        return adaptee.Member1();
    }

    // etc for each member of SealedClass
}