设计模式专栏目录
创建型设计模式-单例模式/工厂模式/抽象工厂
行为型设计模式:模板设计模式/观察者设计模式/策略设计模式
C#反射机制实现开闭原则的简单工厂模式
C#反射
特性(Attribute)
**特性(Attribute)**是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。可以看作我们程序的注释,包含我们程序的一些信息,但是这个注释在运行时其他地方也能看到,并获取到。
using System;
public class MyClass
{
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]
static void OldMethod()
{
Console.WriteLine("It is the old method");
}
static void NewMethod()
{
Console.WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}
}
反射(Reflection)
反射(Reflection)最常见的用途就是它允许在运行时查看特性(attribute)信息;以及允许审查集合中的各种类型,以及实例化这些类型。
例如:
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute//这是一个自定义的特性
{
public readonly string Url;
public string Topic // Topic 是一个命名(named)参数
{
get { return topic; } set { topic = value; }
}
public HelpAttribute(string url) // url 是一个定位(positional)参数
{
this.Url = url;
}
private string topic;
}
[HelpAttribute("Information on the class MyClass")]//创建MyClass的特性
class MyClass
{
}
namespace AttributeAppl
{
class Program
{
static void Main(string[] args)
{
System.Reflection.MemberInfo info = typeof(MyClass);//通过typeof反射机制获取MyClass的类型
object[] attributes = info.GetCustomAttributes(true);//获取特性
for (int i = 0; i < attributes.Length; i++)
{
System.Console.WriteLine(attributes[i]);//打印特性 “HelpAttribute”
}
Console.ReadKey();
}
}
}
运行结果:
HelpAttribute
简单工厂模式&反射
产品类
public abstract class Product
{
protected ControllerBase(string typeName)
{
TypeName = typeName;
}
public abstract void Show();
};
// 产品 A
public class ProductA : Product
{
public class ProductA : base("产品A"){}
public override void Show()
{
System.Console.WriteLine("Product A.");
}
};
// 产品 B
public class ProductB Product
{
public class ProductA : base("产品B"){}
public override void Show()
{
System.Console.WriteLine("Porduct B.");
}
};
工厂类
// 工厂
public class Factory : InstanceBase<ControllerFactory>
{
public Factory()
{
var types = Assembly.GetExecutingAssembly().GetExportedTypes().Where(p => typeof(Product).IsAssignableFrom(p) && !p.IsAbstract && p.IsClass).ToList();
types.ForEach(p =>
{
var instance = (Product)Activator.CreateInstance(p);
_productItems.Add(instance.TypeName, p);
});
}
public Product CreateProduct(string typeName)
{
return (Product)Activator.CreateInstance(_productItems[typeName]);
}
private Dictionary<string, Type> _productItems = new Dictionary<string, Type>();
};
主函数
class Program
{
static void Main(string[] args)
{
ControllerFactory.Instance().CreateProduct("产品A");
ControllerFactory.Instance().CreateProduct("产品B");
}
}
加入需要新增产品类型的话,就可以直接新增继承产品类。而不需要修改工厂类。
文章介绍了设计模式中的创建型和行为型模式,如单例、工厂、模板设计模式等。同时,详细讲解了C#中的反射机制,如何利用反射获取和使用特性信息。此外,文章通过示例展示了如何使用反射实现简单工厂模式,以及如何通过添加新产品类来扩展该模式,无需修改工厂类。
180

被折叠的 条评论
为什么被折叠?



