【发布时间】:2011-06-20 18:16:39
【问题描述】:
在开始描述我的问题之前,我想定义装饰器和扩展方法的定义 装饰器
动态地为对象附加额外的职责。装饰器为扩展功能提供了一种灵活的替代子类的方法
扩展方法
扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型
我在c#中有以下代码sn-p
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);
}
}
在上面的代码中,我在不修改现有代码的情况下扩展接口,这两种方法可用于派生类。所以我的问题是:扩展方法是装饰器模式的替代品吗?
【问题讨论】:
-
可能会发现装饰器模式取代了静态扩展方法,主要是因为静态方法难以测试并且它们增加了耦合。
标签: c# design-patterns