不理解抽象工厂模式是无法彻底明白 Petshop 的,听起来好像名词比较多,不好理解...其实就像一层窗户纸一样!

有两点需要注意一下:
1. 必须明白接口的概念及使用方法
2. IFruit MyFruit = (IFruit)Assembly.Load(path).CreateInstance(sTypeName);
    这一句包含的内容比较多,但是理解了其实也没什么的;
    首先是使用接口声明对象,Assembly 是反射方式加载对象,path 为应用程序的“程序集名称”,sTypeName 为完整的类名
    比方说下面的代码中,程序集的名称在项目属性中指定(我这里使用的和命名空间名称一样),而完整类名就更好理解了!

使用方法:

Code
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label lb 
= new Label();
        
string FruitName = TextBox1.Text.Trim();
        
this.form1.Controls.Add(lb);

        
//声明工厂对象
        FruitFactory MyFruitFactory = new FruitFactory();

        
//以接口方式声明对象(可以实例化为此接口的任何一个对象)
        IFruit MyFruit = MyFruitFactory.MakeFruit(FruitName);

        
//调用对象内的方法
        lb.Text = MyFruit.PostName();
    }

 

工厂定义如下:

Code
using System.Reflection;

namespace vopt.DAL
{
    
/// <summary>
    
/// 抽象接口定义
    
/// </summary>
    public interface IFruit
    {
        
string PostName();//返回类名
    }

    
/// <summary>
    
/// 实例类型一
    
/// </summary>
    public class Orange : IFruit
    {
        
public string PostName()
        {
            
return this.ToString();//返回类名
        }
    }

    
/// <summary>
    
/// 实例类型二
    
/// </summary>
    public class Apple : IFruit
    {
        
public string PostName()
        {
            
return this.ToString();//返回类名
        }

    }

    
/// <summary>
    
/// 抽象工厂定义
    
/// </summary>
    public class FruitFactory
    {
        
public IFruit MakeFruit(string className)
        {
            
//程序集名称
            string path = "vopt.DAL";

            
//完整的类名,vopt.DAL.Apple/Orange
            string sTypeName = path + "." + className;

            
//利用反射加载对象
            IFruit MyFruit = (IFruit)Assembly.Load(path).CreateInstance(sTypeName);

            
return MyFruit;
        }
    }
}

posted on 2009-01-20 15:21  jarod99  阅读(1769)  评论(0编辑  收藏  举报