抽象工廠模式(Abstract Factory Pattern)屬於『創建型模式』。
提供一個創建一系列相關或相互依賴的對象接口,無須指定他們具體類。
(資料來源:維基百科)
public interface Shape {
public void draw();
}
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("畫一個圓形");
}
}
public class Square implements Shape{
@Override
public void draw() {
System.out.println("畫一個正方形");
}
}
public interface Color {
public void fill();
}
public class Red implements Color{
@Override
public void fill() {
System.out.println("塗上紅色");
}
}
public class White implements Color{
@Override
public void fill() {
System.out.println("塗上白色");
}
}
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape);
}
public class ShapeFactory extends AbstractFactory{
@Override
Color getColor(String color) {
return null;
}
@Override
Shape getShape(String shapeType) {
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
public class ColorFactory extends AbstractFactory{
@Override
Color getColor(String color) {
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
}else if(color.equalsIgnoreCase("WHITE")){
return new White();
}
return null;
}
@Override
Shape getShape(String shape) {
return null;
}
}
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
}else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}
public static void main(String[] args) {
AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
Color color1 = colorFactory.getColor("RED");
color1.fill();
Color color2 = colorFactory.getColor("WHITE");
color2.fill();
}
畫一個圓形
畫一個正方形
塗上紅色
塗上白色