常州市做网站的公司,做视频网站设备需求,室内设计学院,怎么做app推广代理文章目录 一. 简单工厂#xff08;Simple Factory#xff09;第一种简单工厂#xff1a;面向接口编程与工厂类#xff1a;划分功能职责第二种#xff1a;单例简单工厂#xff1a;节省内存和对象创建的时间 二. 工厂方法#xff08;Factory Method#xff09;#xff1… 文章目录 一. 简单工厂Simple Factory第一种简单工厂面向接口编程与工厂类划分功能职责第二种单例简单工厂节省内存和对象创建的时间 二. 工厂方法Factory Method进一步抽象通过面向接口的思路创建对象三. 什么时候使用工厂方法四. 抽象工厂 一般情况下工厂模式分为三种更加细分的类型简单工厂、工厂方法和抽象工厂。
什么时候该用工厂模式相对于直接 new 来创建对象用工厂模式来创建究竟有什么好处呢这是本文将要讨论的事情。 一. 简单工厂Simple Factory
第一种简单工厂面向接口编程与工厂类划分功能职责
如下代码流程描述了根据不同的文件后缀面向接口编程创建不同的对象然后执行相同方法的不同逻辑。
public class RuleConfigSource {public RuleConfig load(String ruleConfigFilePath) {//1. 获取文件后缀String ruleConfigFileExtension getFileExtension(ruleConfigFilePath);//这个是函数式接口有一个抽象方法parse。//2. 根据不同的文件后缀创建不同的parse对象面向接口编程IRuleConfigParser parser null;if (json.equalsIgnoreCase(ruleConfigFileExtension)) {parser new JsonRuleConfigParser();} else if (xml.equalsIgnoreCase(ruleConfigFileExtension)) {parser new XmlRuleConfigParser();} else if (yaml.equalsIgnoreCase(ruleConfigFileExtension)) {parser new YamlRuleConfigParser();} else if (properties.equalsIgnoreCase(ruleConfigFileExtension)) {parser new PropertiesRuleConfigParser();} else {throw new InvalidRuleConfigException(Rule config file format is not supported: ruleConfigFilePath);}//3. 根据具体实现解析文本String configText ;//从ruleConfigFilePath文件中读取配置文本到configText中RuleConfig ruleConfig parser.parse(configText);return ruleConfig;}private String getFileExtension(String filePath) {//...解析文件名获取扩展名比如rule.json返回jsonreturn json;}
} 为了增加代码的可读性将功能独立的代码封装成函数将创建对象的逻辑抽取出来 public RuleConfig load(String ruleConfigFilePath) {String ruleConfigFileExtension getFileExtension(ruleConfigFilePath);//1. 创建对象IRuleConfigParser parser createParser(ruleConfigFileExtension);//check parsernullString configText ;//从ruleConfigFilePath文件中读取配置文本到configText中//2. 执行指定对象的parse方法面向接口编程RuleConfig ruleConfig parser.parse(configText);return ruleConfig;}private String getFileExtension(String filePath) {//...解析文件名获取扩展名比如rule.json返回jsonreturn json;}private IRuleConfigParser createParser(String configFormat) {IRuleConfigParser parser null;if (json.equalsIgnoreCase(configFormat)) {parser new JsonRuleConfigParser();} else if (xml.equalsIgnoreCase(configFormat)) {parser new XmlRuleConfigParser();} else if (yaml.equalsIgnoreCase(configFormat)) {parser new YamlRuleConfigParser();} else if (properties.equalsIgnoreCase(configFormat)) {parser new PropertiesRuleConfigParser();}return parser;}
}类责任单一对象创建的方法放到独立一个类中具体地 将 createParser() 函数剥离到一个独立的类中让这个类只负责对象的创建。
...public class RuleConfigParserFactory {public static IRuleConfigParser createParser(String configFormat) {IRuleConfigParser parser null;if (json.equalsIgnoreCase(configFormat)) {parser new JsonRuleConfigParser();} else if (xml.equalsIgnoreCase(configFormat)) {parser new XmlRuleConfigParser();} else if (yaml.equalsIgnoreCase(configFormat)) {parser new YamlRuleConfigParser();} else if (properties.equalsIgnoreCase(configFormat)) {parser new PropertiesRuleConfigParser();}return parser;}
}
类名与方法名 大部分工厂类都是以“Factory”这个单词结尾的但也不是必须的比如 Java 中的 DateFormat、Calender。工厂类中创建对象的方法一般都是 create 开头比如代码中的 createParser()但有的也命名为 getInstance()、createInstance()、newInstance()有的甚至命名为 valueOf()比如 Java String 类的 valueOf() 函数等等这个我们根据具体的场景和习惯来命名就好。 面向接口编程 面向接口编程Interface-Oriented Programming其核心思想是依赖于接口或抽象类来编写程序而不是依赖于具体的实现类。具体地通过接口来串联起业务代码的逻辑而不是具体的实现类。 面向接口有如下好处
松耦合各个模块之间的依赖关系更松散。这使得系统中的组件可以更独立地开发、测试和部署可扩展性新的功能可以通过实现现有接口来扩展系统而不会影响到已有的代码。增强代码复用通过面向接口编程可以提高代码的可重用性。不同的实现类可以实现相同的接口使得同一份代码可以适应不同的实际需求。测试和调试面向接口编程使得单元测试更加容易可以使用模拟对象mock objects来模拟接口的行为从而进行更有效的单元测试和调试。 第二种单例简单工厂节省内存和对象创建的时间
为了节省内存和对象创建的时间我们可以将 parser 事先创建好缓存起来。当调用 createParser() 函数的时候我们从缓存中取出 parser 对象直接使用。
public class RuleConfigParserFactory {private static final MapString, RuleConfigParser cachedParsers new HashMap();static {cachedParsers.put(json, new JsonRuleConfigParser());cachedParsers.put(xml, new XmlRuleConfigParser());cachedParsers.put(yaml, new YamlRuleConfigParser());cachedParsers.put(properties, new PropertiesRuleConfigParser());}public static IRuleConfigParser createParser(String configFormat) {if (configFormat null || configFormat.isEmpty()) {return null;//返回null还是IllegalArgumentException全凭你自己说了算}//也去掉了if elseIRuleConfigParser parser cachedParsers.get(configFormat.toLowerCase());return parser;}
}对于上面两种简单工厂模式的实现方法如果我们要添加新的 parser那势必要改动到 RuleConfigParserFactory 的代码那这是不是违反开闭原则呢实际上如果不是需要频繁地添加新的 parser只是偶尔修改一下 RuleConfigParserFactory 代码稍微不符合开闭原则也是完全可以接受的。 总结一下尽管简单工厂模式的代码实现中有多处 if 分支判断逻辑违背开闭原则但权衡扩展性和可读性这样的代码实现在大多数情况下比如不需要频繁地添加 parser也没有太多的 parser是没有问题的。 二. 工厂方法Factory Method进一步抽象通过面向接口的思路创建对象
如果我们非得要将 if 分支逻辑去掉那该怎么办呢比较经典处理方法就是利用多态。按照多态的实现思路对上面的代码进行重构。
如下我们新增一个创建对象的工厂这样当我们新增一种 parser 的时候只需要新增一个实现了 IRuleConfigParserFactory 接口的 Factory 类即可。所以工厂方法模式比起简单工厂模式更加符合开闭原则。
public interface IRuleConfigParserFactory {IRuleConfigParser createParser();
}public class JsonRuleConfigParserFactory implements IRuleConfigParserFactory {Overridepublic IRuleConfigParser createParser() {return new JsonRuleConfigParser();}
}XmlRuleConfigParserFactory
YamlRuleConfigParserFactory
...-------------public class RuleConfigSource {public RuleConfig load(String ruleConfigFilePath) {String ruleConfigFileExtension getFileExtension(ruleConfigFilePath);IRuleConfigParserFactory parserFactory null;if (json.equalsIgnoreCase(ruleConfigFileExtension)) {parserFactory new JsonRuleConfigParserFactory();} else if (xml.equalsIgnoreCase(ruleConfigFileExtension)) {parserFactory new XmlRuleConfigParserFactory();} else if (yaml.equalsIgnoreCase(ruleConfigFileExtension)) {parserFactory new YamlRuleConfigParserFactory();} else if (properties.equalsIgnoreCase(ruleConfigFileExtension)) {parserFactory new PropertiesRuleConfigParserFactory();} else {throw new InvalidRuleConfigException(Rule config file format is not supported: ruleConfigFilePath);}// 这里是工厂方法的关键思路点通过面向接口的思路来创建对象IRuleConfigParser parser parserFactory.createParser();String configText ;RuleConfig ruleConfig parser.parse(configText);return ruleConfig;}}但注意代码的复杂度此时增加了 工厂类对象的创建逻辑又耦合进了 load() 函数中跟我们最初的代码版本非常相似引入工厂方法非但没有解决问题反倒让设计变得更加复杂了。 我们为工厂类再创建一个简单工厂也就是工厂的工厂用来创建工厂类对象。 public class RuleConfigSource {public RuleConfig load(String ruleConfigFilePath) {String ruleConfigFileExtension getFileExtension(ruleConfigFilePath);IRuleConfigParserFactory parserFactory RuleConfigParserFactoryMap.getParserFactory(ruleConfigFileExtension);if (parserFactory null) {throw new InvalidRuleConfigException(Rule config file format is not supported: ruleConfigFilePath);}IRuleConfigParser parser parserFactory.createParser();String configText ;//从ruleConfigFilePath文件中读取配置文本到configText中RuleConfig ruleConfig parser.parse(configText);return ruleConfig;}private String getFileExtension(String filePath) {//...解析文件名获取扩展名比如rule.json返回jsonreturn json;}
}//因为工厂类只包含方法不包含成员变量完全可以复用
//不需要每次都创建新的工厂类对象所以简单工厂模式的第二种实现思路更加合适。
public class RuleConfigParserFactoryMap { //工厂的工厂private static final MapString, IRuleConfigParserFactory cachedFactories new HashMap();static {cachedFactories.put(json, new JsonRuleConfigParserFactory());cachedFactories.put(xml, new XmlRuleConfigParserFactory());cachedFactories.put(yaml, new YamlRuleConfigParserFactory());cachedFactories.put(properties, new PropertiesRuleConfigParserFactory());}public static IRuleConfigParserFactory getParserFactory(String type) {if (type null || type.isEmpty()) {return null;}IRuleConfigParserFactory parserFactory cachedFactories.get(type.toLowerCase());return parserFactory;}
}当我们需要添加新的规则配置解析器的时候我们只需要创建新的 parser 类和 parser factory 类并且在 RuleConfigParserFactoryMap 类中将新的 parser factory 对象添加到 cachedFactories 中即可。代码的改动非常少基本上符合开闭原则。 三. 什么时候使用工厂方法
实际上对于规则配置文件解析这个应用场景来说工厂模式需要额外创建诸多 Factory 类也会增加代码的复杂性而且每个 Factory 类只是做简单的 new 操作功能非常单薄只有一行代码也没必要设计成独立的类所以在这个应用场景下简单工厂模式简单好用比工厂方法模式更加合适。 那什么时候该用工厂方法模式而非简单工厂模式呢
如果代码块本身并不复杂就几行代码而已我们完全没必要将它拆分成单独的函数或者类。当对象的创建逻辑比较复杂不只是简单的 new 一下就可以而是要组合其他类对象做各种初始化操作的时候我们推荐使用工厂方法模式将复杂的创建逻辑拆分到多个工厂类中让每个工厂类都不至于过于复杂。比如不同jdbc数据源的管理、flink connector的管理。 四. 抽象工厂
抽象工厂模式的应用场景比较特殊没有前两种常用。
在简单工厂和工厂方法中类只有一种分类方式。当有多个类的分类时我们可以让一个工厂负责创建多个不同类型的对象而不是只创建一种 parser 对象。如下
public interface IConfigParserFactory {IRuleConfigParser createRuleParser();ISystemConfigParser createSystemParser();//此处可以扩展新的parser类型比如IBizConfigParser
}public class JsonConfigParserFactory implements IConfigParserFactory {Overridepublic IRuleConfigParser createRuleParser() {return new JsonRuleConfigParser();}Overridepublic ISystemConfigParser createSystemParser() {return new JsonSystemConfigParser();}
}...
XmlConfigParserFactory
YamlConfigParserFactory
PropertiesConfigParserFactory参考 王争《设计模式之美》