开放/封闭原则-如何处理此开关? [英] Open / Closed Principle - How to deal with this Switch?

查看:92
本文介绍了开放/封闭原则-如何处理此开关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究开放式封闭原则,这听起来不错,所以我想行使它的教s. 我考虑将新发现的知识应用到现有项目中,并立即变得有些困惑.

I have been looking into the open closed principle and it sounds good and so I wanted to exercise it's teachings. I looked at applying my new found knowledge to an existing project and have become a little stuck right away.

如果出现了新的UserType(并且很有可能),则需要对其进行更改,但尚未进行修改.谁能解决这个问题?

If a new UserType comes along (And this is Very likely), this will need to be changed, it is not yet closed to modification. How could one get round this?

从我读到的内容来看,听起来应该在这里实施工厂而不是应用OCP?

From what I have read, it sounds like I should be implementing a factory here instead of applying the OCP?

违反了开放封闭原则的工厂

 private void BuildUserTree(User user)
    {
        switch (user.UserType)
        {
            case UserType.FreeLoader:
                BuildFreeLoaderTree();
                break;
            case UserType.Premium:
                BuildPremiumTree();
                break;
            case UserType.Unlimited:
                BuildUnlimitedTree();
                break;
            default:
                throw new Exception("No UserType set");

        }
    }

谢谢, 可汗

推荐答案

像任何原则" OCP一样,并不是您必须在任何情况下都必须遵守的规则.

Like any 'principle' OCP is not a rule that you must obey on all occasions.

我们被告知要偏重于继承而不是继承",但是诸如装饰器和合成器之类的模式会公开地促进继承.

We're told to 'Favour composition over inheritance', and yet patterns like decorator and composite openly promote inheritance.

类似地,我们被告知对接口进行编程,而不是对实现进行编程,但是,在我们的应用程序中的某个时候,我们将不得不实例化具有某种描述的具体对象.

Similarly, we are told to 'Program to an interface, not an implemenation, and yet, at some point in our application we're going to have to instantiate a concrete object of some description.

您的解决方案是经典的工厂习语(如果不是完全的工厂方法或抽象工厂模式).这就是要这样做的.尝试对其应用OCP没有任何意义.

Your solution is a classic factory idiom (if not quite the full factory method or abstract factory pattern). This is what it is intended to do. Trying to apply OCP to it doesn't make sense.

实际上,通过创建此方法,您实际上可以在代码库的其他部分使用OCP.现在,您已经将创建分离了,您的应用程序中的某些其他类现在可以遵循OCP.

In fact, by creating this method, you may actually facilitate OCP in some other part of your code-base. Some other class or classes in your app could now obey OCP now you have separated the creation.

这篇关于开放/封闭原则-如何处理此开关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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