| 编程中国 | 业界新闻 | 技术文章 | 视频教程 | 下载频道 | 程序源码 | 个人空间 | 编程论坛
全能ASP/PHP/ASP.NET主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付买域名,送MP3、MP4
高端软件开发 = 年薪十万不是梦赛孚耐:软件保护加密专家身份认证令牌USB KEY买空间,免费送域名(厦门中资源)
共有 308 人关注过本帖
标题:利用反射实现工厂模式.
收藏  订阅  推荐  打印 
ioriliao
Rank: 12Rank: 12Rank: 12
来自:广东
等级:贵宾
威望:29
帖子:2122
积分:23963
注册:2006-11-30
利用反射实现工厂模式.

//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-8-22 12:01
jfwsp
Rank: 1
等级:新手上路
帖子:10
积分:200
注册:2008-9-22
回复 1# ioriliao 的帖子

还是没有明白你想表达干什么意思呀
2008-9-23 00:55
关于我们 | 广告合作 | 编程中国 | 清除Cookies | Archiver | WAP | TOP

编程中国 版权所有,并保留所有权利。鲁ICP备08000592号
Powered by Discuz, Processed in 0.049155 second(s), 9 queries.
Copyright©2004-2008, BCCN.NET, All Rights Reserved