• 简单工厂和工厂模式


    简单工厂

    首先是一个引入的例子,在这段代码中,根据配置文件的后缀选择不同的解析器。将存储在文件中的配置解析成内存对象RuleConfig

    1. public class RuleConfigSource {
    2. public RuleConfig load(String ruleConfigFilePath) {
    3. String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);
    4. IRuleConfigParser parser = null;
    5. if ("json".equalsIgnoreCase(ruleConfigFileExtension)) {
    6. parser = new JsonRuleConfigParser();
    7. } else if ("xml".equalsIgnoreCase(ruleConfigFileExtension)) {
    8. parser = new XmlRuleConfigParser();
    9. } else if ("yaml".equalsIgnoreCase(ruleConfigFileExtension)) {
    10. parser = new YamlRuleConfigParser();
    11. } else if ("properties".equalsIgnoreCase(ruleConfigFileExtension)) {
    12. parser = new PropertiesRuleConfigParser();
    13. } else {
    14. throw new InvalidRuleConfigException(
    15. "Rule config file format is not supported: " + ruleConfigFilePath);
    16. }
    17. String configText = "";
    18. //从ruleConfigFilePath文件中读取配置文本到configText中
    19. RuleConfig ruleConfig = parser.parse(configText);
    20. return ruleConfig;
    21. }
    22. private String getFileExtension(String filePath) {
    23. //...解析文件名获取扩展名,比如rule.json,返回json
    24. return "json";
    25. }
    26. }

    第一次优化:将上边代码中涉及parser创建的部分剥离出来,抽象成createParser()函数。重构之后的代码如下所示:

    1. public RuleConfig load(String ruleConfigFilePath) {
    2. String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);
    3. IRuleConfigParser parser = createParser(ruleConfigFileExtension);
    4. if (parser == null) {
    5. throw new InvalidRuleConfigException(
    6. "Rule config file format is not supported: " + ruleConfigFilePath);
    7. }
    8. String configText = "";
    9. //从ruleConfigFilePath文件中读取配置文本到configText中
    10. RuleConfig ruleConfig = parser.parse(configText);
    11. return ruleConfig;
    12. }
    13. private String getFileExtension(String filePath) {
    14. //...解析文件名获取扩展名,比如rule.json,返回json
    15. return "json";
    16. }
    17. private IRuleConfigParser createParser(String configFormat) {
    18. IRuleConfigParser parser = null;
    19. if ("json".equalsIgnoreCase(configFormat)) {
    20. parser = new JsonRuleConfigParser();
    21. } else if ("xml".equalsIgnoreCase(configFormat)) {
    22. parser = new XmlRuleConfigParser();
    23. } else if ("yaml".equalsIgnoreCase(configFormat)) {
    24. parser = new YamlRuleConfigParser();
    25. } else if ("properties".equalsIgnoreCase(configFormat)) {
    26. parser = new PropertiesRuleConfigParser();
    27. }
    28. return parser;
    29. }
    30. }

    第二次优化:为了让类的职责更加单一、代码更加清晰,还可以把createParser()函数放到一个独立的类中,让这个类只负责对象的创建。而这个类就是简单工厂类

    1. public class RuleConfigSource {
    2. public RuleConfig load(String ruleConfigFilePath) {
    3. String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);
    4. IRuleConfigParser parser = RuleConfigParserFactory.createParser(ruleConfigFileExtension);
    5. if (parser == null) {
    6. throw new InvalidRuleConfigException(
    7. "Rule config file format is not supported: " + ruleConfigFilePath);
    8. }
    9. String configText = "";
    10. //从ruleConfigFilePath文件中读取配置文本到configText中
    11. RuleConfig ruleConfig = parser.parse(configText);
    12. return ruleConfig;
    13. }
    14. private String getFileExtension(String filePath) {
    15. //...解析文件名获取扩展名,比如rule.json,返回json
    16. return "json";
    17. }
    18. }
    19. public class RuleConfigParserFactory {
    20. public static IRuleConfigParser createParser(String configFormat) {
    21. IRuleConfigParser parser = null;
    22. if ("json".equalsIgnoreCase(configFormat)) {
    23. parser = new JsonRuleConfigParser();
    24. } else if ("xml".equalsIgnoreCase(configFormat)) {
    25. parser = new XmlRuleConfigParser();
    26. } else if ("yaml".equalsIgnoreCase(configFormat)) {
    27. parser = new YamlRuleConfigParser();
    28. } else if ("properties".equalsIgnoreCase(configFormat)) {
    29. parser = new PropertiesRuleConfigParser();
    30. }
    31. return parser;
    32. }
    33. }

    上边是第一种实现简单工厂模式的方法,下边是第二种实现简单工厂模式的方法

    1. public class RuleConfigParserFactory {
    2. private static final Map<String, RuleConfigParser> cachedParsers = new HashMap<>();
    3. static {
    4. cachedParsers.put("json", new JsonRuleConfigParser());
    5. cachedParsers.put("xml", new XmlRuleConfigParser());
    6. cachedParsers.put("yaml", new YamlRuleConfigParser());
    7. cachedParsers.put("properties", new PropertiesRuleConfigParser());
    8. }
    9. public static IRuleConfigParser createParser(String configFormat) {
    10. if (configFormat == null || configFormat.isEmpty()) {
    11. return null;//返回null还是IllegalArgumentException全凭你自己说了算
    12. }
    13. IRuleConfigParser parser = cachedParsers.get(configFormat.toLowerCase());
    14. return parser;
    15. }
    16. }

    对于上边两种简单工厂模式的实现方法,如果要添加新的parser,那么必然要改动Factory类的代码。这样虽然看起来违反了开闭原则,但是如果不是频繁地添加新的parser,只是偶尔修改一下Factory代码,稍微不符合开闭原则也是可以接受的。

    初次之外,在第一种实现中,如果不if分支不是很多,代码中有if也是没问题的。使用多态或者设计模式来代替if判断也有缺点:虽然提高了代码的扩展性,更加符合开闭原则,但是也增加了类的个数,牺牲了代码的可读性。

    工厂方法

    如果非要去掉if分支,那么比较经典的处理方法就是利用多态。按照多态的实现思路,对上边的代码进行重构

    1. public interface IRuleConfigParserFactory {
    2. IRuleConfigParser createParser();
    3. }
    4. public class JsonRuleConfigParserFactory implements IRuleConfigParserFactory {
    5. @Override
    6. public IRuleConfigParser createParser() {
    7. return new JsonRuleConfigParser();
    8. }
    9. }
    10. public class XmlRuleConfigParserFactory implements IRuleConfigParserFactory {
    11. @Override
    12. public IRuleConfigParser createParser() {
    13. return new XmlRuleConfigParser();
    14. }
    15. }
    16. public class YamlRuleConfigParserFactory implements IRuleConfigParserFactory {
    17. @Override
    18. public IRuleConfigParser createParser() {
    19. return new YamlRuleConfigParser();
    20. }
    21. }
    22. public class PropertiesRuleConfigParserFactory implements IRuleConfigParserFactory {
    23. @Override
    24. public IRuleConfigParser createParser() {
    25. return new PropertiesRuleConfigParser();
    26. }
    27. }

    这就是工厂方法模式的典型代码实现,这样我们新增一种parser的时候。只需要新增一个实现了IRuleConfigParserFactory接口的Factory类即可。所以,工厂方法模式比简单工厂模式更符合开闭原则。

    从上边的工厂方法的实现来看是没有问题的。但是在这些工厂类的使用上还存在问题,代码如下

    1. public class RuleConfigSource {
    2. public RuleConfig load(String ruleConfigFilePath) {
    3. String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);
    4. IRuleConfigParserFactory parserFactory = null;
    5. if ("json".equalsIgnoreCase(ruleConfigFileExtension)) {
    6. parserFactory = new JsonRuleConfigParserFactory();
    7. } else if ("xml".equalsIgnoreCase(ruleConfigFileExtension)) {
    8. parserFactory = new XmlRuleConfigParserFactory();
    9. } else if ("yaml".equalsIgnoreCase(ruleConfigFileExtension)) {
    10. parserFactory = new YamlRuleConfigParserFactory();
    11. } else if ("properties".equalsIgnoreCase(ruleConfigFileExtension)) {
    12. parserFactory = new PropertiesRuleConfigParserFactory();
    13. } else {
    14. throw new InvalidRuleConfigException("Rule config file format is not supported: " + ruleConfigFilePath);
    15. }
    16. IRuleConfigParser parser = parserFactory.createParser();
    17. String configText = "";
    18. //从ruleConfigFilePath文件中读取配置文本到configText中
    19. RuleConfig ruleConfig = parser.parse(configText);
    20. return ruleConfig;
    21. }
    22. private String getFileExtension(String filePath) {
    23. //...解析文件名获取扩展名,比如rule.json,返回json
    24. return "json";
    25. }
    26. }

    从这段代码来看,工厂类对象的创建逻辑又耦合到了load()函数中,和最开始的代码非常相似,引入工厂方法非但没有解决问题,反而让设计更加复杂了。如何解决?

    解决方案是为工厂类再创建一个简单工厂,也就是工厂的工厂,用来创建工厂类对象。

    1. public class RuleConfigSource {
    2. public RuleConfig load(String ruleConfigFilePath) {
    3. String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);
    4. IRuleConfigParserFactory parserFactory = RuleConfigParserFactoryMap.getParserFactory(ruleConfigFileExtension);
    5. if (parserFactory == null) {
    6. throw new InvalidRuleConfigException("Rule config file format is not supported: " + ruleConfigFilePath);
    7. }
    8. IRuleConfigParser parser = parserFactory.createParser();
    9. String configText = "";
    10. //从ruleConfigFilePath文件中读取配置文本到configText中
    11. RuleConfig ruleConfig = parser.parse(configText);
    12. return ruleConfig;
    13. }
    14. private String getFileExtension(String filePath) {
    15. //...解析文件名获取扩展名,比如rule.json,返回json
    16. return "json";
    17. }
    18. }
    19. //因为工厂类只包含方法,不包含成员变量,完全可以复用,
    20. //不需要每次都创建新的工厂类对象,所以,简单工厂模式的第二种实现思路更加合适。
    21. public class RuleConfigParserFactoryMap { //工厂的工厂
    22. private static final Map<String, IRuleConfigParserFactory> cachedFactories = new HashMap<>();
    23. static {
    24. cachedFactories.put("json", new JsonRuleConfigParserFactory());
    25. cachedFactories.put("xml", new XmlRuleConfigParserFactory());
    26. cachedFactories.put("yaml", new YamlRuleConfigParserFactory());
    27. cachedFactories.put("properties", new PropertiesRuleConfigParserFactory());
    28. }
    29. public static IRuleConfigParserFactory getParserFactory(String type) {
    30. if (type == null || type.isEmpty()) {
    31. return null;
    32. }
    33. IRuleConfigParserFactory parserFactory = cachedFactories.get(type.toLowerCase());
    34. return parserFactory;
    35. }
    36. }

    当我们需要添加新的规则配置解析器的时候,只需要创建新的parser类和新的parserfactory类,并且在RuleConfigParserFactoryMap类中把新的parser factory对象添加到map中即可。代码的改动非常少,基本符合开闭原则

    实际上,对于规则配置文件解析这个场景来说,工厂模式需要额外创建很多factory类,也会增加代码的复杂性。而且每个工厂类只是做简单的new操作,也没必要设计成独立的类。所以在这个应用场景下,简单工厂模式简单好用,比工厂方法模式更加合适。

    什么时候使用简单工厂,什么时候使用工厂

    之前说到,之所以将某个代码块抽出来作为独立的函数或者类,是因为这个代码块的逻辑过于复杂,剥离之后能让代码更加可读、清晰。反之如果代码就几行,那么没必要抽出来。

    当对象的创建逻辑比较复杂,不只是简单的new一下就可以,而是要组合其他类对象,做各种初始化操作的时候,我们推荐使用工厂方法模式,将复杂的创建逻辑拆分到多个工厂类中,让每个工厂类都不至于过于复杂。而使用简单工厂时,将所有的创建逻辑都放在一个工厂类中,会让这个类复杂。

    此外,在某些场景下,如果对象不可复用,那么工厂类每次都要返回新的对象。如果使用简单工厂模式来实现,那么只能选择第一种if分支的方式。如果还想进一步避免if分支,那么就使用工厂模式。

    和建造者模式的区别

    工厂模式是用来创建不同但是类型相关的对象(继承同一个父类或者实现了同一个接口的类),由给定的参数来决定创建哪种类型的对象。建造者模式是用来创建一种类型的复杂对象,通过设置不同的可选参数,定制化的创建不同对象

    打个比方:顾客走进一家饭店,我们利用工厂模式,根据顾客不同的选择来制作不同的食物,如碧汉堡、披萨、沙拉。对于披萨来说,用户又有各种配料可以定制,比如奶酪、西红柿、芝士,我们通过建造者模式根据用户选择的不同配料来制作披萨

  • 相关阅读:
    冰箱压缩机市场现状研究分析与发展前景预测
    如何在 C# 程序中注入恶意 DLL?
    devtools安装
    全球AI人工智能领袖:Anthropic联合创始人丹妮拉·阿莫迪!
    scanf、printf使用详解
    实验9 静态路由配置
    【Windows】bat批处理程序简单应用
    Postgresql事务测试
    Dubbo使用invoke指令来调用dubbo接口
    【Flink实战】用户统计:按照省份维度统计新老用户
  • 原文地址:https://blog.csdn.net/CHN_ZHero/article/details/127709881