工厂模式是一种创建模式,因为此模式提供了更好的方法来创建对象。
在工厂模式中,我们创建对象而不将创建逻辑暴露给客户端。
在以下部分中,我们将展示如何使用工厂模式创建对象。
由工厂模式创建的对象将是形状对象,如圆形,矩形。
首先,我们设计一个接口来表示Shape。
public interface Shape {void run();
}
然后我们创建三个实现接口的具体类。
以下代码用于Rectangle.java
public class Rectangle implements Shape {public void run() {System.out.println("Rectangle");}
}
Square.java
public class Square implements Shape {public void run() {System.out.println("Square");}
}
Circle.java
public class Circle implements Shape {public void run() {System.out.println("Circle");}
}
工厂模式的核心是一个Factory类。以下代码显示了如何为Shape对象创建Factory类。
ShapeFactory类基于传递给getShape()方法的String值创建Shape对象。如果String值为CIRCLE,它将创建一个Circle对象。
public class ShapeFactory {private Map map = new HashMap();public ShapeFactory() {map.put("rectangle",new Rectangle());map.put("square",new Square());map.put("circle",new Circle());}public Shape getShape(String type) {return map.get(type);}
}
我们在工厂类里面构造一个方法来存放我们工厂所有的实现类,这里不一定这样写,只要在调用getShape方法的时候能够根据不同的类型拿到对应的实现类工厂就可以了,有的这样写也可以,只是不太优雅而已
public class ShapeFactory {public Shape getShape(String shapeType){if(shapeType == null){return null;} if(shapeType.equalsIgnoreCase("circle")){return new Circle();} else if(shapeType.equalsIgnoreCase("rectangle")){return new Rectangle();} else if(shapeType.equalsIgnoreCase("square")){return new Square();}return null;}
}
接下来我们来测试一下工厂模式
以下代码具有main方法,并且它使用Factory类通过传递类型等信息来获取具体类的对象。
public class TestDemo
{public static void main(String [] args){ShapeFactory shapeFactory = new ShapeFactory();Shape rectangle = shapeFactory.getShape("rectangle");rectangle.run();Shape circle = shapeFactory.getShape("circle");circle.run();Shape square = shapeFactory.getShape("square");square.run();}
}
上面的代码生成以下结果。
总结:工厂模式就是多个实现类继承一个接口类实现同一个接口,工厂类初始化所有实现类,并标记不同实现类,调用是根据标记获得实现类执行方法。
下一篇:Python练习题