依赖倒转原则讲的是:要依赖于抽象,不要信赖于实现。 这是为实现开闭原则的一种手段。
比如之前的代码,我们的主程序中:
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;
}
}
扫描二维码关注公众号,回复:
711443 查看本文章
抽象工厂模式,直接从别人哪儿拷贝来的代码
-
- public interface Plant {
- }
-
-
- public class PlantA implements Plant {
-
- public PlantA() {
- System.out.println( " create PlantA ! " );
- }
-
- public void doSomething() {
- System.out.println( " PlantA do something " );
- }
- }
-
- public class PlantB implements Plant {
- public PlantB() {
- System.out.println( " create PlantB ! " );
- }
-
- public void doSomething() {
- System.out.println( " PlantB do something " );
- }
- }
-
-
- public interface Fruit {
- }
-
-
- public class FruitA implements Fruit {
- public FruitA() {
- System.out.println( " create FruitA ! " );
- }
-
- public void doSomething() {
- System.out.println( " FruitA do something " );
- }
- }
-
- public class FruitB implements Fruit {
- public FruitB() {
- System.out.println( " create FruitB ! " );
- }
-
- public void doSomething() {
- System.out.println( " FruitB do something " );
- }
- }
-
-
- public interface AbstractFactory {
- public Plant createPlant();
-
- public Fruit createFruit();
- }
-
-
- public class FactoryA implements AbstractFactory {
- public Plant createPlant() {
- return new PlantA();
- }
-
- public Fruit createFruit() {
- return new FruitA();
- }
- }
-
- public class FactoryB implements AbstractFactory {
- public Plant createPlant() {
- return new PlantB();
- }
-
- public Fruit createFruit() {
- return new FruitB();
- }
- }