装饰器模式和装饰器模式C# 中的扩展方法

发布于 2024-10-15 21:13:55 字数 1132 浏览 1 评论 0原文

在首先描述我的问题之前,我想定义装饰器和扩展方法的定义 装饰器

动态地将附加职责附加到对象。装饰器为扩展功能提供了子类化的灵活替代方案

扩展方法

扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型

我在 C# 中有以下代码片段

public interface IMyInterface
{
    void Print();
}

public static class Extension
{
    public static void PrintInt(this IMyInterface myInterface, int i)
    {
        Console.WriteLine
            ("Extension.PrintInt(this IMyInterface myInterface, int i)");
    }

    public static void PrintString(this IMyInterface myInterface, string s)
    {
        Console.WriteLine
            ("Extension.PrintString(this IMyInterface myInterface, string s)");
    }
}

public class Imp : IMyInterface
{
    #region IMyInterface Members

    public void Print()
    {
        Console.WriteLine("Imp");
    }

    #endregion
}

class Program
{
    static void Main(string[] args)
    {
        Imp obj = new Imp();
        obj.Print();
        obj.PrintInt(10);
    }
}

在上面的代码中,我在不修改现有代码的情况下扩展接口,并且这些派生类可以使用两种方法。所以我的问题是:扩展方法是否可以替代装饰器模式?

Before going to describe my problem first,I would like to define definitions of Decorator and Extension method
Decorator

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality

Extension method

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type

I have following code snippet in c#

public interface IMyInterface
{
    void Print();
}

public static class Extension
{
    public static void PrintInt(this IMyInterface myInterface, int i)
    {
        Console.WriteLine
            ("Extension.PrintInt(this IMyInterface myInterface, int i)");
    }

    public static void PrintString(this IMyInterface myInterface, string s)
    {
        Console.WriteLine
            ("Extension.PrintString(this IMyInterface myInterface, string s)");
    }
}

public class Imp : IMyInterface
{
    #region IMyInterface Members

    public void Print()
    {
        Console.WriteLine("Imp");
    }

    #endregion
}

class Program
{
    static void Main(string[] args)
    {
        Imp obj = new Imp();
        obj.Print();
        obj.PrintInt(10);
    }
}

In the above code I am extending interface without modifying the existing code,and these two methods are available to derived class. So my question is this: Is the extension method a replacement of the decorator pattern?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不奢求什么 2024-10-22 21:13:55

扩展方法实际上只是调用静态方法的语法糖。

虽然使用装饰器实际上可以更改装饰类的行为,但扩展方法只能更改类上的属性或调用方法,就像“普通”静态方法一样。

装饰器模式实际上被定义为使用包装器来改变行为,而扩展方法显然不这样做。

A extension method is really just syntactic sugar for calling a static method.

While with a decorator you could actually change the behaviour of your decorated class, a extension method could only alter properties or call methods on your class, just like an "ordinary" static method.

Decorator pattern is actually definied as using a wrapper to alter behaviour, which a extension method clearly doesn't do.

夏の忆 2024-10-22 21:13:55

您会错过装饰器模式的动态部分。扩展方法是在编译时定义的静态野兽,可以使用或不使用......但不能在运行时修改/交换。

Ýou miss the dynamic part of the decorator pattern. Extension methods are static beasts defined at compile time and can be used or not... but not modified / exchanged at runtime.

双马尾 2024-10-22 21:13:55

扩展方法不能替代装饰器模式。扩展方法可以为现有类型提供功能,而无需创建派生类型。

这与装饰器模式的传统实现不同。装饰器模式允许您在运行时动态地向对象提供多种行为,而无需为这些行为的每种组合创建一个新的子类。

Extension methods are not a replacement for the decorator pattern. Extension methods work to provide functionality to an existing type without having to create a derived type.

This is different from the traditional implementation to the decorator pattern. The decorator pattern allows you to dynamically provide multiple behaviors to an object at runtime without having to create a new subclass for each combination of those behaviors.

圈圈圆圆圈圈 2024-10-22 21:13:55

扩展方法是装饰者模式还是访问者模式?读完后我会说它更类似于访客。

引用维基百科的伟大之处,维基百科从来没有错误:P

在面向对象编程和软件工程中,访问者
设计模式是一种将算法与对象分离的方法
它运行的结构。这种分离的实际结果是
能够向现有对象结构添加新操作,而无需
修改这些结构。这是轻松遵循的一种方法
开放/封闭原则。本质上,访问者允许添加新的
在不修改类的情况下将虚函数添加到一系列类中
他们自己;相反,我们创建一个访问者类来实现所有
虚函数的适当专业化。这
访问者将实例引用作为输入,并实现目标
通过双重调度。

Extension method a Decorator pattern or a Visitor pattern? After reading I would say its more akin to the Visitor.

Quoting the greatness that is wikipedia, the pedia that never has errors :P

In object-oriented programming and software engineering, the visitor
design pattern is a way of separating an algorithm from an object
structure it operates on. A practical result of this separation is the
ability to add new operations to existing object structures without
modifying those structures. It is one way to easily follow the
open/closed principle. In essence, the visitor allows one to add new
virtual functions to a family of classes without modifying the classes
themselves; instead, one creates a visitor class that implements all
of the appropriate specializations of the virtual function. The
visitor takes the instance reference as input, and implements the goal
through double dispatch.

任谁 2024-10-22 21:13:55

Erich Gamma (GoF) 的解释似乎是最好的... http://www.mif.vu.lt/~plukas/resources/Extension%20Objects/ExtensionObjectsPattern%20Gamma96.pdf

本质上说明了

a) 结合所有操作并说明不同的客户端(现在和将来)需要集成到单个界面中会导致界面臃肿

b) 所需的操作(已知和未知)可以分类为组件。可以从中定义一个(或多个)组件接口(扩展接口)。这些可能会或可能不会由对象(当前和未来)实现。

c) 希望使用此扩展接口的客户端可以查询组件是否支持它

d) 最后,此扩展接口有一个公共基类(ComponentExtension),具有最小的接口来管理扩展本身(检查扩展是否存在,通知扩展)即将被删除)

在以下情况下使用:

1 当您现有的类可能需要额外不可预见接口(即新的、当前的)未知的行为模式)。

2 当代表关键抽象的类为不同的客户端扮演不同的(不可预见的和开放式的)角色时。

3 您希望扩展而不需要子类

它类似于以下模式

Visitor 需要稳定的类层次结构和引入依赖循环

Decorator,使用更加透明,接口狭窄,现有操作应增强

Adapter,支持现有接口

This explanation by Erich Gamma (GoF) seems to be the best... http://www.mif.vu.lt/~plukas/resources/Extension%20Objects/ExtensionObjectsPattern%20Gamma96.pdf

Essentially stating that

a) Combining all the operations and state that the different clients (present and future) need into a single interface results in a bloated interface

b) Desired operations (known and unknown) can be categorized into components. From which one (or more) Component Interfaces) (extended interfaces) can be defined. These may or may not be implemented by objects (current and future).

c) Clients that wish to use this extended interface can query whether a component supports it

d) Finally, this extended interface has a common base class (ComponentExtension) with minimal interface to manage the extension itself (checking if an extension exists, informing the extension that it is about to be deleted)

To be used when:

1 When your existing classes may need additional and unforeseen interfaces (i.e. new, currently unknown patterns of behavior).

2 When a class representing a key abstraction plays different (unforeseen & open-ended) roles for different clients.

3 You wish to extend without sub-classing

It is similar to the following patterns

Visitor which needs stable class hierarchy & introduces dependency cycle

Decorator where the use is more transparent, the interface is narrow and existing operations should be augmented

Adapter which supports EXISTING interfaces

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文