| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1432 人关注过本帖
标题:利用反射实现工厂模式.
只看楼主 加入收藏
ioriliao
Rank: 7Rank: 7Rank: 7
来 自:广东
等 级:贵宾
威 望:32
帖 子:2829
专家分:647
注 册:2006-11-30
结帖率:78.95%
收藏
 问题点数:0 回复次数:1 
利用反射实现工厂模式.
//ICar.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ICar
{
    public interface ICar
    {
        string GetCar();
    }
}


//FuTe.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FuTe
{
    public class FuTe : ICar.ICar
    {
   
        public string GetCar()
        {
            return "FuTe";
        }
    }
}


//CarFactory.dll
using System;
using System.Reflection;

namespace CarFactory
{
    public class CarFactory
    {

        public static ICar.ICar CreateCar(string CarFileName)
        {
            var CarAssembly = Assembly.LoadFrom(CarFileName);
            ICar.ICar CarType = null;
            foreach (var tmpCarType in CarAssembly.GetTypes())
            {
                    CarType = (ICar.ICar)Activator.CreateInstance(tmpCarType);
                    break;
            }
            return CarType;
        }
    }
}

//ConsoleApplication6.exe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            var myCar = CarFactory.CarFactory.CreateCar(@"FuTe.dll");
            var CarName = myCar.GetCar();
            Console.WriteLine(CarName);
            Console.ReadLine();
        }
    }
}

如果CarFactory.CarFactory.CreateCar(这里是相对路径,那么请把ConsoleApplication6.exe和所有dll放在同一个文件夹)
此例子简单,我觉得足以表达思想.
有不明白请提问.
搜索更多相关主题的帖子: 工厂 反射 模式 
2008-08-22 12:01
jfwsp
Rank: 1
等 级:新手上路
帖 子:10
专家分:0
注 册:2008-9-22
收藏
得分:0 
回复 1# ioriliao 的帖子
还是没有明白你想表达干什么意思呀
2008-09-23 00:55
快速回复:利用反射实现工厂模式.
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.023173 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved