---
title: "工厂模式"
author: "Jameslyy"
date: "2007-07-31T11:55:26Z"
tags: ["工作", "编程"]
slug: "untitled"
draft: false
lastmod: "2007-07-31T11:55:26Z"
id: 107340
url: "https://jamesblog.iteye.com/blog/107340"
---

一般建立对象的方法是： Sample sample ＝ **new** Sample(); 通过new关键词和类的构造方法来建立一个对象，可以通过向构造方法传递参数，并在构造方法中完成一些初始化的工作。但是，如果初始化的工作非常多，采用这样的方法实在不是明智的，而应该采用将创建实例的工作与使用实例的工作分开的原则，而这就是工厂模式。

        工厂模式用于创建复杂的对象，创建复杂的对象是指在创建对象时需要大量的初始化工作。工厂模式将创建实例的工作与使用实例的工作分开。在一个接口拥有多个实现类时也可以使用工厂模式来建立子类的对象。

        按照面向接口编程的原则，我们可以把功能类抽象成接口。首先建立一个接口Sample，假如Sample有两个实现类SampleA和SampleB，创建SampleA和SampleB的工厂方法如下：

java 代码

1. public class Factory {
2. public static Sample createSample(int which){
3. if (which==1) {
4. return new SampleA();
5. } else if (which==2)
6. return new SampleB();
7. }
8. }
9. }

这样就可以调用Factory.createSample(1)来创建对象了。

**抽象工厂**  
        工厂模式中有: 工厂方法(Factory Method) 抽象工厂(Abstract Factory)。抽象工厂(Abstract Factory)处理更为复杂对象创建工作。

![](http://dev.yesky.com/imagelist/06/28/87cmo0e86rm1.gif)

       例：

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. }

        工厂方法模式与简单工厂模式再结构上的不同不是很明显。工厂方法类的核心是一个抽象工厂类，而简单工厂模式把核心放在一个具体类上。

　　工厂方法模式之所以有一个别名叫多态性工厂模式是因为具体工厂类都有共同的接口，或者有共同的抽象父类。

　　当系统扩展需要添加新的产品对象时，仅仅需要添加一个具体对象以及一个具体工厂对象，原有工厂对象不需要进行任何修改，也不需要修改客户端，很好的符合了"开放－封闭"原则。而简单工厂模式在添加新产品对象后不得不修改工厂方法，扩展性不好。