模式思想
- 約定一個接口
- 定義實現接口的實體類
- 定義用來獲取實體類的工廠類
- 調用工廠類
代碼實現
- 約定接口
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