开关语句是否适用于工厂方法? C# [英] Is a switch statement applicable in a factory method? c#

查看:113
本文介绍了开关语句是否适用于工厂方法? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回一个接口,并在我要设置的switch语句里面。这是一个糟糕的设计吗?

  private IResultEntity GetEntity(char?someType)
{
IResultEntity entity =空值;

switch(someType)
{
case'L':// life
entity = new LifeEntity();
break;
case'P':// property
entity = new PropertyEntity();
break;
case'D':// disability
entity = new DisabilityEntity();
break;
case'C'://信用卡
entity = new CreditCardEntity();
break;
}

返回实体;
}


解决方案

我通常不介意在工厂中切换语句,前提是我可以组合和控制我希望我的工厂提前创建的所有派生类。



有时,也许用户创建的插件可能希望将自己的类添加到该开关列表,然后是一个swich语句是不够的。



我发现这个很好来源的更多信息创建一些更强大/多才多艺的工厂课程



一个好的我通常采取的中间方法是保持静态字典<字符串,类型>为每个工厂类。



人们可以使用某种



pre> Factories.TypeRegistration.StaticDictionary.Add(somekey,typeof(MyDerivedClass))


(或更好的是使用注册方法并隐藏StaticDictionary)



然后,Factory通过执行一个简单的任务来创建一个实例在表中查找:

  Activator.CreateInstance(Factories.TypeRegistration.StaticDictionary [somekey]); 


I want to return an Interface and inside a switch statement I would like to set it. Is this a bad design?

private IResultEntity GetEntity(char? someType)
    {
        IResultEntity entity = null;

        switch (someType)
        {
            case 'L': //life
                entity = new LifeEntity();
                break;
            case 'P': //property
                entity = new PropertyEntity();
                break;
            case 'D': //disability
                entity = new DisabilityEntity();
                break;
            case 'C': //credit card
                entity = new CreditCardEntity();
                break;
        }

        return entity;
    }

解决方案

I don't usually mind switch statements in a factory, provided I can group and control all of the derived classes that I want my factory to create in advance.

Sometimes,maybe a user-created plugin might want to add it's own classes to that switch list, and then a swich statement is not enough.

I found this good source for some more info on creating some more powerfull/versatile factory classes

A good middle-ground approach I usually take is to keep a static Dictionary< string,Type > for each factory class.

People can just "register" their own implementations using some sort of

Factories.TypeRegistration.StaticDictionary.Add("somekey",typeof(MyDerivedClass))

(or better yet, use a Registration method and hide the StaticDictionary)

then the Factory has an easy task of creating an instance by performing a lookup in the table:

Activator.CreateInstance(Factories.TypeRegistration.StaticDictionary["somekey"]);

这篇关于开关语句是否适用于工厂方法? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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