---
title: "依赖倒转原则和工厂模式"
author: "memorymyann"
date: "2011-12-21T14:02:38Z"
tags: []
categories: ["互联网"]
slug: "untitled"
draft: false
lastmod: "2011-12-21T14:07:52Z"
id: 1319454
url: "https://memorymyann.iteye.com/blog/1319454"
---

依赖倒转原则讲的是：要依赖于抽象，不要信赖于实现。 这是为实现开闭原则的一种手段。

 

比如之前的代码，我们的主程序中：

Graph g = new xxx();

......

g.getArea();

 

对g的声明则是Graph，而非具体的三角或者原型。我们下面的一切对g的操作，都是依赖Graph，而非对具体的图形的依赖。但只有在初始化g的时候，我们必须制定三角Graph g = new Triangl()或者圆形Graph g = new Circle();这就和依赖倒转原则冲突。由此引入工厂模式。

 

简单工厂模式：

package sty;

public class GraphFactory {

    public static Graph createGraph(String type) {  
        Graph g = null;  
        if(type.equals("triangle"))  
            g = new Triangle();  
        if(type.equals("Circle"))  
            g = new Circle();  
        return g;  
    }  
}

 

抽象工厂模式，直接从别人哪儿拷贝来的代码

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