说到工厂模式我们一定算是比较大众常见的设计模式,基本是张嘴就来:简单工厂模式,工厂模式,抽象工厂模式。
但是问一下设计模式在构建型设计模式算几个,这三个模式什么样,怎么使用,区别?还有就是分几类?这些清楚吗。所以这边一点点来看工厂模式。
设计模式在构建型设计模式算几个?
我们说常见的资料设计模式23种,但是也有一说是22种,这到底是多少。
23种能数全的一般都是老资料,因为新的说法只有工厂模式和抽象工厂模式,少了个简单工厂自然就23-1变成22了。这里有一个国外的设计模式的学习网站可以研究看一下,内容算是比较新比较全的。最起码首页的图挺全的,里面讲解也都有图配,没有那么干燥。
设计模式学习
三种工厂模式的形式:
简答模式,说句通俗的话就是,把一些ifelse的逻辑给搬出去,放在一个地方就可以。talk is cheap ,show me code
以下都是小争哥的专栏的代码,这里主要是关于不同文件的解析的逻辑代码,而弄的一个简单工厂模式
public class RuleConfigSource {
public RuleConfig load(String ruleConfigFilePath) {
String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);
IRuleConfigParser parser = RuleConfigParserFactory.createParser(ruleConfigFileExtension);
if (parser == null) {
throw new InvalidRuleConfigException(
"Rule config file format is not supported: " + ruleConfigFilePath);
}
String configText = "";
//从ruleConfigFilePath文件中读取配置文本到configText中
RuleConfig ruleConfig = parser.parse(configText);
return ruleConfig;
}
private String getFileExtension(String filePath) {
//...解析文件名获取扩展名,比如rule.json,返回json
return "json";
}
}
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() 函数)等等,这个我们根据具体的场景和习惯来命名就好。
这是大概的规律,命名这个是这样的,看你尊不遵守,你也管不了别人。
设计模式在使用的过程从来不是单独的使用的,比如说我们上次说单例模式可以通过工厂模式做成多例的



