---
title: "设计模式-抽象工厂模式"
author: "yeaijun"
date: "2011-01-20T15:57:52Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2011-01-20T15:58:45Z"
id: 889950
url: "https://yeaijun.iteye.com/blog/889950"
---

1.概念   
《设计模式》一书中对于抽象工厂模式是这样定义的：提供一个创建一系列相关或相互依赖对象的接口，而无需指定它们具体的类。 

2、示例 

Java代码 

01. // 产品 Plant接口
02. public interface Plant { }//标志接口
03. //具体产品PlantA，PlantB
04. public class PlantA implements Plant {
05. public PlantA () {
06. System.out.println("create PlantA !");
07. }
08. public void doSomething() {
09. System.out.println(" PlantA do something ...");
10. }
11. }
12. public class PlantB implements Plant {
13. public PlantB () {
14. System.out.println("create PlantB !");
15. }
16. public void doSomething() {
17. System.out.println(" PlantB do something ...");
18. }
19. }
20. // 产品 Fruit接口
21. public interface Fruit { }
22. //具体产品FruitA，FruitB
23. public class FruitA implements Fruit {
24. public FruitA() {
25. System.out.println("create FruitA !");
26. }
27. public void doSomething() {
28. System.out.println(" FruitA do something ...");
29. }
30. }
31. public class FruitB implements Fruit {
32. public FruitB() {
33. System.out.println("create FruitB !");
34. }
35. public void doSomething() {
36. System.out.println(" FruitB do something ...");
37. }
38. }
39. // 抽象工厂方法
40. public interface AbstractFactory {
41. public Plant createPlant();
42. public Fruit createFruit();
43. }
44. //具体工厂方法
45. public class FactoryA implements AbstractFactory {
46. public Plant createPlant() {
47. return new PlantA();
48. }
49. public Fruit createFruit() {
50. return new FruitA();
51. }
52. }
53. public class FactoryB implements AbstractFactory {
54. public Plant createPlant() {
55. return new PlantB();
56. }
57. public Fruit createFruit() {
58. return new FruitB();
59. }
60. }

Java代码 

1. //调用工厂方法
2. public Client {
3. public method1() {
4. AbstractFactory instance = new FactoryA();
5. instance.createPlant();
6. }
7. }

3、抽象工厂模式与工厂方法模式的区别   
可以这么说，工厂方法模式是一种极端情况的抽象工厂模式，而抽象工厂模式可以看成是工厂方法模式的一种推广。   
(1)、其实工厂方法模式是用来创建一个产品的等级结构的，而抽象工厂模式是用来创建多个产品的等级结构的。工厂方法创建一般只有一个方法，创建一种产品。抽象工厂一般有多个方法，创建一系列产品。   
(2)、工厂方法模式只有一个抽象产品类，而抽象工厂模式有多个。工厂方法模式的具体工厂类只能创建一个具体产品类的实例，而抽象工厂模式可以创建多个。 

简而言之-&gt;   
工厂方法模式：一个抽象产品类，可以派生出多个具体产品类。     
              一个抽象工厂类，可以派生出多个具体工厂类。     
              每个具体工厂类只能创建一个具体产品类的实例。     
抽象工厂模式：多个抽象产品类，每个抽象产品类可以派生出多个具体产品类。     
              一个抽象工厂类，可以派生出多个具体工厂类。     
              每个具体工厂类可以创建多个具体产品类的实例。