依赖倒转原则和工厂模式

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

比如之前的代码,我们的主程序中:

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

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

  1. //  产品 Plant接口         
  2. public   interface  Plant {   
  3. }   
  4.   
  5. // 具体产品PlantA,PlantB   
  6. public   class  PlantA  implements  Plant {   
  7.   
  8.      public  PlantA() {   
  9.         System.out.println( " create PlantA ! " );   
  10.     }   
  11.   
  12.      public   void  doSomething() {   
  13.         System.out.println( "  PlantA do something  " );   
  14.     }   
  15. }   
  16.   
  17. public   class  PlantB  implements  Plant {   
  18.      public  PlantB() {   
  19.         System.out.println( " create PlantB ! " );   
  20.     }   
  21.   
  22.      public   void  doSomething() {   
  23.         System.out.println( "  PlantB do something  " );   
  24.     }   
  25. }   
  26.   
  27. // 产品 Fruit接口   
  28. public   interface  Fruit {   
  29. }   
  30.   
  31. // 具体产品FruitA,FruitB   
  32. public   class  FruitA  implements  Fruit {   
  33.      public  FruitA() {   
  34.         System.out.println( " create FruitA ! " );   
  35.     }   
  36.   
  37.      public   void  doSomething() {   
  38.         System.out.println( "  FruitA do something  " );   
  39.     }   
  40. }   
  41.   
  42. public   class  FruitB  implements  Fruit {   
  43.      public  FruitB() {   
  44.         System.out.println( " create FruitB ! " );   
  45.     }   
  46.   
  47.      public   void  doSomething() {   
  48.         System.out.println( "  FruitB do something  " );   
  49.     }   
  50. }   
  51.   
  52. // 抽象工厂方法   
  53. public   interface  AbstractFactory {   
  54.      public  Plant createPlant();   
  55.   
  56.      public  Fruit createFruit();   
  57. }   
  58.   
  59. // 具体工厂方法   
  60. public   class  FactoryA  implements  AbstractFactory {   
  61.      public  Plant createPlant() {   
  62.          return   new  PlantA();   
  63.     }   
  64.   
  65.      public  Fruit createFruit() {   
  66.          return   new  FruitA();   
  67.     }   
  68. }   
  69.   
  70. public   class  FactoryB  implements  AbstractFactory {   
  71.      public  Plant createPlant() {   
  72.          return   new  PlantB();   
  73.     }   
  74.   
  75.      public  Fruit createFruit() {   
  76.          return   new  FruitB();   
  77.     }   
  78. }  

猜你喜欢

转载自memorymyann.iteye.com/blog/1319454