违反开闭原则的工厂 [英] Factory which breaks Open-closed principle

查看:134
本文介绍了违反开闭原则的工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象工厂/工厂方法的经典实现基于多态。但是在最低级别上,我们必须拥有某种工厂,该工厂不基于多态性并且会打破开放式封闭原则:

Classical implementation of Abstract Factory/Factory method is based on polymorphism. But on the lowest level we have to have some kind of factory which is not based on polymorphism and breaks open-closed principle:

public Device Create(string deviceName)
{
  switch (deviceName)
  {
    case "Device1": return new Device1();
    case "Device2": return new Device2()'
    default: throw new NotSupportedDeviceException(deviceName);
  }
}

这类工厂是否有特殊名称?

Is there any special name for this kind of factories?

推荐答案

据我所知,您已经发布了一个非常有效的Factory Method模式示例:

From what I can see, you've posted a perfectly valid example of the Factory Method pattern:


  • Device1和Device2都继承/实现Device类/接口-多态性仍然是此示例的关键方面。

  • 您正在使用Factory方法封装逻辑,以确定要实例化并返回哪个具体类。

  • factory方法的调用者仍然非常不清楚所涉及的具体类-他只是知道他拿回了设备。

是的,内部实现有点笨拙(开关盒)。但是,这并不能使它成为真正的Factory Method模式。

It's true, the internal implementation is a little heavy-handed (switch-case). However, that doesn't make it any less of a true Factory Method pattern.

我真的看不到您的示例不是基于多态性的,也不是。它违反了开放/封闭原则。如果我完全忘记了要点,请随时更新您的帖子,以帮助我们将您的问题归零。

I don't really see where your example "isn't based on polymorphism" nor where it "breaks the open/closed principle". If I've missed the point entirely, feel free to update your post, to help us zero in on your question.

现在,如果Factory方法采用传递的deviceName ,并使用它找到要实例化的具体类的精确匹配(使用反射),这绝对会破坏Factory Method模式,因为调用者必须对不同具体类有深入的了解。但是,按照目前的说法,传递的deviceName只是决策过程中使用的一条数据-不会破坏工厂模式的封装。

Now if the Factory method was taking the passed deviceName, and using it to find an exact match of the concrete class to instantiate (using reflection), that would absolutely break the Factory Method pattern, because the caller would have to have intimate knowledge of the different concrete classes. But as currently written, the passed deviceName is just a piece of data used in the decision-making process - it doesn't break the encapsulation of the factory pattern.

这篇关于违反开闭原则的工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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