模式思想
- 约定一个接口
- 定义实现接口的实体类
- 定义用来获取实体类的工厂类
- 调用工厂类
代码实现
- 约定接口
package factory;
public interface Shape {
void draw();
}
- 实现接口的实体类
package factory;
public class Circle implements Shape {
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
package factory;
public class Rectangle implements Shape {
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
package factory;
public class Square implements Shape {
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
- 定义工厂类
package factory;
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;
}
}
- 调用工厂类
import factory.Shape;
import factory.ShapeFactory;
public class FactoryDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shapeCircle = shapeFactory.getShape("Circle");
shapeCircle.draw();
Shape shapeRectangle = shapeFactory.getShape("Rectangle");
shapeRectangle.draw();
Shape shapeSquare = shapeFactory.getShape("Square");
shapeSquare.draw();
}
}
指导文档
http://www.runoob.com/design-pattern/factory-pattern.html