简单工厂与反思C# [英] Simple Factory with reflection C#

查看:123
本文介绍了简单工厂与反思C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用反射的简单工厂涉及将各种类型的名称与其对应的类类型存储(注册)在散列表中,然后使用此散列表在工厂中生成对象。

Simple factory using reflection involves storing (registering) various type names with their corresponding class type in a hash table, then using this hash table for generating objects in the factory.

interface Product
{
    void foo();
}
class ProductFactory
{
    HashTable m_RegisteredProducts = new HashTable();
    public void registerProduct(string productID, Type p)    {
        m_RegisteredProducts.add(productID, p);
    }

    public Product createProduct(string productID){
        return (Product) new m_RegisteredProducts[productID];
    }
}

我不清楚什么时候注册新的类型发生,因为要使用的所有类型都将在运行时加载到散列表中。调用registerProduct()的方式在哪里?

I'm not clear on when does the process of registering a new type happen since all types to be used are to be loaded into the hash table at runtime. Where is the call to registerProduct() to be made?


  1. 在ProductFactory类中的单个位置调用registerProduct()没有意义,因为它会击败使用反思的原理,在初始切换/案例方法的目的。

  2. 如果在实现接口的所有类的类定义中调用registerProduct()


推荐答案

这取决于有不同的场景需要不同的策略。
如果所有产品类型都在同一个程序集(或程序集列表)中定义,那么我经常看到的一个策略是这样的:

It depends. There are different scenarios that call for different strategies. One strategy that I saw quite often if all product types are defined in the same assembly (or a list of assemblies) you could call something like this:

var productTypes= from t in Assembly.GetExecutingAssembly().GetTypes()
                  where t.GetInterfaces().Contains(typeof(IProduct));

,然后为productTypes中的每个元素调用registerProduct()。

and then call registerProduct() for every element in productTypes.

这篇关于简单工厂与反思C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆