分类
- 简单工厂模式
- 工厂方法模式
- 抽象工厂模式
解决的问题
初始化对象经常造成“耦合”问题,工厂模式主要解决复杂的依赖问题。
思考
代码分为两类:
框架代码——内容代码
整体架构——架构血肉
局部架构——局部血肉
页面架构——页面血肉
- 框架代码:写完后不应再频繁修改,对扩展开发,对修改关闭。
- 内容代码:产生具体数据的地方,new应该放到这里。
针对接口编程
可以隔离掉以后系统可能发生的一大堆改变。为什么?如果代码是针对接口而写,那么通过多态,它可以与任何新类实现该接口。但是,当代码使用大量的具体类时,等于是自找麻烦,因为一旦加入新的具体类,就必须改变代码。应该对扩展开放对修改关闭,重点在于这些都是说的框架代码。加入新的具体类,代码必须被修改,但修改应该发生于内容代码部分。
简单工厂
类图
image.png
伪代码
public class Customer{
SimpleFactory factory;
public Customer(SimpleFactory factory){
this.factory = factory;
}
public Product createProduct(String type){
Product pdt = factory.createProduct(type);// 增加新具体类,此处不用修改,框架代码。
xxxxxx
}
}
工厂:处理创建对象的细节
public class SimpleFactory{
public Product createProduct(String type){
Product pdt = null;
if(type="aaa"){
pdt = new Product1();
}else if(type="bbb"){
pdt = new Product2();
}
//以后再增加新的具体类,这里修改。因为这里是产生具体内容的代码。
}
}
简单工厂的特点:
- 封装了变化
- 对象组合方式,非继承方式
- 另一个类专门控制对象创建
工厂方法模式
类图
image.png
伪代码
public abstract class Customer{
public abstract Product createProduct();
}
public class class CustomerLetter extends Customer{
public Product createProduct(String type){
if(type == "a")return new ProductA();
if(type == "b")return new ProductB();
if(type == "c")return new ProductC();
}
}
工厂方法模式特点:
- 子类继承父类,并重写父类创造对象的方法。
- 父类不关心创建对象的细节,只知道要拿到一个对象。
- 子类关心创造对象的细节,关心具体创建哪个对象。
- 所有子类创建的对象都属于一个继承体系Product,但子类之间的对象又有一些差别。
抽象工厂模式
定义
提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体的类。
抽象工厂允许客户使用抽象的接口来创建一组相关的产品,而不需要关心实际产出的具体产品是什么。这样一来,客户就从具体的产品中被解耦。
类图
image.png
伪代码
public interface AbstractFactory{
public Element1 createElement1();
public Element2 createElement2();
public Element3 createElement3();
public Element4 createElement4();
public Element5 createElement5();
}
public class ElementFactoryA implements AbstractFactory{
public Element1 createElement1(){
return new Element1A();
}
public Element2 createElement2(){
return new Element2A();
}
......
}
public class ElementFactoryB implements AbstractFactory{
public Element1 createElement1(){
return new Element1B();
}
public Element2 createElement2(){
return new Element2B();
}
......
}
使用:
AbstractFactory af = new ElementFactoryA();
Product pa = new ProductChildA( af );// ProductChildA 使用了ElementFactoryA提供的所有Elements
AbstractFactory af2 = new ElementFactoryB();
Product pb = new ProductChildB( af2 );// ProductChildB 使用了ElementFactoryB提供的所有Elements
抽象工厂模式特点
- 工厂方法模式,是一个接口方法提供一个产品。
- 抽象工厂模式,是一组接口方法提供一组产品。组中的一个接口方法,又是由工厂方法实现。
使用场景
- 工厂方法,把客户代码从需要实例化的具体类中解耦。或者如果你目前还不知道将来需要实例化哪些具体类时,也可以使用。定义一个抽象方法,让子类实现具体类型。
- 抽象工厂,当你需要创建产品家族和想让制造的相关产品集合起来时使用。









网友评论