using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace NET.MST.Sixth.ReflectionFactory
{
/// <summary>
/// 使用者
/// </summary>
class Customer
{
static void Main(string[] args)
{
//使用者的代碼和傳統實現一樣
IProduct window = FactoryManager.GetProduct(RoomParts.Window);
IProduct pillar = FactoryManager.GetProduct(RoomParts.Pillar);
IProduct roof = FactoryManager.GetProduct(RoomParts.Roof);
Console.Read();
}
}
/// <summary>
/// 工廠管理類型
/// </summary>
class FactoryManager
{
public static IProduct GetProduct(RoomParts part)
{
Factory factory = new Factory();
IProduct product = factory.Produce(part);
Console.WriteLine("生產了一個產品:" +
product.GetName());
return product;
}
}
/// <summary>
/// 屋子產品的零件
/// </summary>
enum RoomParts
{
Roof,
Window,
Pillar
}
/// <summary>
/// 這個特性用來附加在產品類型之上,
/// 來標註該類型代碼哪個產品,方便反射使用
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
class ProductAttribute : Attribute
{
//標註零件的成員
private RoomParts _myRoomPart;
public ProductAttribute(RoomParts part)
{
_myRoomPart = part;
}
public RoomParts RoomPart
{
get
{
return _myRoomPart;
}
}
}
/// <summary>
/// 這個特性用來附加在產品介面之上
/// 來標註一共實現了多少產品零件,方便反射使用
/// </summary>
[AttributeUsage(AttributeTargets.Interface)]
class ProductListAttribute : Attribute
{
private Type[] _myList;
public ProductListAttribute(Type[] Products)
{
_myList = Products;
}
public Type[] ProductList
{
get
{
return _myList;
}
}
}
#region 產品類族
/// <summary>
/// 產品零件介面,
/// 需要添加所有實現該介面的列表
/// </summary>
[ProductList(new Type[]{
typeof(Roof),
typeof(Window),
typeof(Pillar)})]
interface IProduct
{
String GetName();
}
/// <summary>
/// 屋頂類型
/// </summary>
[ProductAttribute(RoomParts.Roof)]
class Roof : IProduct
{
public String GetName()
{
return "屋頂";
}
}
/// <summary>
/// 窗戶類型
/// </summary>
[Product(RoomParts.Window)]
class Window : IProduct
{
public String GetName()
{
return "窗戶";
}
}
/// <summary>
/// 柱子類型
/// </summary>
[ProductAttribute(RoomParts.Pillar)]
class Pillar : IProduct
{
public String GetName()
{
return "柱子";
}
}
#endregion
#region 工廠類
/// <summary>
/// 工廠類型,這裡不再需要一個類族,
/// 而只需要一個工廠類型
/// </summary>
class Factory
{
public IProduct Produce(RoomParts part)
{
//通過反射,從IProduct 介面中獲得屬性,
//從而獲得所有的產品零件列表
ProductListAttribute Attr = (ProductListAttribute)
Attribute.GetCustomAttribute(typeof(IProduct),
typeof(ProductListAttribute));
//遍曆所有的實現產品零件類型
foreach (Type type in Attr.ProductList)
{
//利用反射尋找其屬性
ProductAttribute pa = (ProductAttribute)
Attribute.GetCustomAttribute(
type, typeof(ProductAttribute));
//確定是否是需要的零件
if (pa.RoomPart == part)
{
//再一次利用反射
//建立產品零件類型
Object product = Assembly.GetExecutingAssembly().
CreateInstance(type.FullName);
return product as IProduct;
}
}
//不應該到達這裡
return null;
}
}
#endregion
}