Discuz!NT
欢迎 游客 , 注册 | 登录 | 会员 | 界面 | 简洁版本 | 在线 | 帮助
商都网教育宝典宝库

发表新主题 回复该主题
本主题被查看1298次, 共1个帖子, 1页, 当前为第1页     选择页数: 1      跳转到第   上一主题   下一主题
标题: 反射工厂与泛型工厂
张小峰
超级版主
UID: 14
来自:
精华: 4
积分: 313
帖子: 285
注册: 2007-8-23 10:27:00
状态: 离线
威望: 8.00
金钱: 75.55 元
只看楼主 2007-09-24 08:50
反射工厂与泛型工厂
反射工厂:
using System;
using System.Collections.Generic;
using System.Text;

using System.Reflection;

namespace 工厂模式
{
    class Program
    {
        static void Main(string[] args)
        {
            交通工具 a = new 由工具类型产生工具(typeof(卡车));
            a.创建交通工具();
            交通工具 b = new 由工具类型产生工具(typeof(轿车));
            b.创建交通工具();
            Console.Read();
        }
    }

    interface 交通工具
    {
        void 创建交通工具();
    }

    class 由工具类型产生工具 : 交通工具
    {
        Type 工具类型;

        public 由工具类型产生工具(Type 工具类型)
        {
            this.工具类型 = 工具类型;
        }

        public void 创建交通工具()
        {
            object _obj = Activator.CreateInstance(工具类型);
        }
    }

    class 卡车
    {
        public 卡车()
        {
            Console.WriteLine("卡车");
        }
    }

    class 轿车
    {
        public 轿车()
        {
            Console.WriteLine("轿车");
        }
    }
}重构为泛型工厂:
using System;
using System.Collections.Generic;
using System.Text;

//using System.Reflection;

namespace 工厂模式
{
    class Program
    {
        static void Main(string[] args)
        {
            交通工具 a = new 泛型工厂<卡车>();
            a.创建交通工具();

            交通工具 b = new 泛型工厂<轿车>();
            b.创建交通工具();

            Console.Read();
        }
    }

    interface 交通工具
    {
        void 创建交通工具();
    }

    class 泛型工厂<工具类型> : 交通工具 where 工具类型: new()
    {
        public 泛型工厂()
        { }

        public void 创建交通工具()
        {
            工具类型 工具 = new 工具类型();
        }
    }

    class 卡车
    {
        public 卡车()
        {
            Console.WriteLine("卡车");
        }
    }

    class 轿车
    {
        public 轿车()
        {
            Console.WriteLine("轿车");
        }
    }
}
#1  
发表新主题 回复该主题
本主题被查看1298次, 共1个帖子, 1页, 当前为第1页     选择页数: 1      跳转到第







现在的时间是 2008-09-08 11:43:56

版权所有 商都网教育宝典
         Powered by Discuz!NT 1.0.6666    Copyright © 2001-2008 Comsenz Inc.
Processed in 0 seconds