目录
1.什么是工厂方法模式
为了解决简单工厂模式违背开闭原则的问题,对简单工厂模式进一步抽象化,使系统在不修改原来代码的情况下引进新的产品,即满足开闭原则。
2.优缺点
优点: 新增产品时新增工厂类就可以无须修改工厂代码,灵活性增强。同时满足高内聚,低耦合特性
缺点:1.类的数量容易过多,增加复杂度
2.抽象工厂只能生产一种商品
3.适用场景
客户不关心创建产品的细节,只关心产品的品牌
4.工厂模式的角色
抽象产品,具体产品参考简单工厂模式
抽象工厂:
public interface FactoryMethod {
/**
* 获取职业
*
* @return 职业消息
*/
Profession getProfession();
}
具体工厂:
public class DeveloperFactory implements FactoryMethod {
@Override
public Profession getProfession() {
return new Developer();
}
}
public class TesterFactory implements FactoryMethod {
@Override
public Profession getProfession() {
return new Tester();
}
}
工厂方法模式测试:
public class FactoryMethodMain {
public static void main(String[] args) {
new DeveloperFactory().getProfession().outDesc();
new TesterFactory().getProfession().outDesc();
}
}
更多详细扩展代码:
gitlhub项目地址:https://github.com/foralllove/my-utils