设计模式系列:抽象工厂模式

概念

抽象工厂模式在原有的工厂方法模式上扩展,在工厂方面进行了抽象。从而增加产品规格的需求,可以更高地抽象成增加工厂类型。降低了耦合。

实现

类图

图片

代码

Factory

1
2
3
4
5
6
public interface Factory {

public Product createSoftProduct();

public Product createHardProduct();
}

FactoryA

1
2
3
4
5
6
7
8
9
10
11
12
public class ProductFactoryA implements Factory {

public Product createSoftProduct() {
System.out.println("工厂A:");
return new SoftProductA();
}

public Product createHardProduct() {
System.out.println("工厂A:");
return new HardProductA();
}
}

FactoryB

1
2
3
4
5
6
7
8
9
10
11
12
13
public class ProductFactoryB implements Factory {


public Product createSoftProduct() {
System.out.println("工厂B:");
return new SoftProductB();
}

public Product createHardProduct() {
System.out.println("工厂B:");
return new HardProductB();
}
}

Product

1
2
3
public interface Product {
public String getName();
}

ProductB

1
2
3
4
5
6
public class ProductB implements Product {

public String getName() {
return "我是产品B";
}
}

SoftProductB

1
2
3
4
5
6
7
8
9
10
public class SoftProductB extends ProductB {

public SoftProductB() {
System.out.println("创建 产品B:特性:柔软");
}

public String getName() {
return super.getName() + "柔软";
}
}

HardProductB

1
2
3
4
5
6
7
8
9
public class HardProductB extends ProductB {

public HardProductB() {
System.out.println("创建 产品B:特性:坚硬");
}
public String getName() {
return super.getName() + "坚硬";
}
}

ProductA

1
2
3
4
5
6
public class ProductA implements Product {

public String getName() {
return "我是产品A";
}
}

SoftProductA

1
2
3
4
5
6
7
8
9
10
public class SoftProductA extends ProductA {

public SoftProductA() {
System.out.println("创建 产品A:特性:柔软");
}

public String getName() {
return super.getName() + "柔软";
}
}

HardProductA

1
2
3
4
5
6
7
8
9
10
public class HardProductA extends ProductA {

public HardProductA() {
System.out.println("创建 产品A:特性:坚硬");
}

public String getName() {
return super.getName() + "坚硬";
}
}

Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Client {

public static void main(String[] args) {
Factory factoryA = new ProductFactoryA();
Factory factoryB = new ProductFactoryB();
Product productAHard = factoryA.createHardProduct();
System.out.println(productAHard.getName());
Product productBHard = factoryB.createHardProduct();
System.out.println(productBHard.getName());
Product productASoft = factoryA.createSoftProduct();
System.out.println(productASoft.getName());
Product productBSoft = factoryB.createSoftProduct();
System.out.println(productBSoft.getName());
}

}

场景

如上产品 族 A B都有两个子类型,或者说特性。Hard or Soft。如果某个时候业务需求添加产品族C。此时扩展就很方便了,只要实现产品C的工厂类,就可以。
不用修改原来的代码,耦合度低。

总结

抽象工厂
优点: 扩展产品族(类型)容易
缺点: 扩展产品族下的子产品难,需要整体结构调整。