设计模式(五)工厂模式

2019-06-26  本文已影响0人  天色将变
分类
解决的问题

初始化对象经常造成“耦合”问题,工厂模式主要解决复杂的依赖问题。

思考

代码分为两类:
框架代码——内容代码

整体架构——架构血肉
局部架构——局部血肉
页面架构——页面血肉

针对接口编程

可以隔离掉以后系统可能发生的一大堆改变。为什么?如果代码是针对接口而写,那么通过多态,它可以与任何新类实现该接口。但是,当代码使用大量的具体类时,等于是自找麻烦,因为一旦加入新的具体类,就必须改变代码。应该对扩展开放对修改关闭,重点在于这些都是说的框架代码。加入新的具体类,代码必须被修改,但修改应该发生于内容代码部分。

简单工厂

类图
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();
  }
}

工厂方法模式特点:

抽象工厂模式

定义

提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体的类。
抽象工厂允许客户使用抽象的接口来创建一组相关的产品,而不需要关心实际产出的具体产品是什么。这样一来,客户就从具体的产品中被解耦。

类图
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

抽象工厂模式特点

使用场景

上一篇 下一篇

猜你喜欢

热点阅读