package com.factory;/*** Created by 16114 on 2019/5/30.*/
public interface Shape {void draw();
}
創建實現接口的實體類 Rectangle.java、Square.java、Circle.java
package com.factory;/*** Created by 16114 on 2019/5/30.*/
public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Inside Rectangle::draw() method.");}
}
package com.factory;/*** Created by 16114 on 2019/5/30.*/
public class Square implements Shape {@Overridepublic void draw() {System.out.println("Inside Square::draw() method.");}
}
package com.factory;/*** Created by 16114 on 2019/5/30.*/
public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Inside Circle::draw() method.");}
}
創建一個工廠,生成基于給定信息的實體類的對象 ShapeFactory.java
package com.factory;/*** Created by 16114 on 2019/5/30.*/
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;}
}
使用該工廠,通過傳遞類型信息來獲取實體類的對象。FactoryPatternDemo.java
package com.factory;/*** Created by 16114 on 2019/5/30.*/
public class FactoryPatternDemo {public static void main(String[] args) {ShapeFactory shapeFactory =new ShapeFactory();Shape shape1 = shapeFactory.getShape("CIRCLE");shape1.draw();Shape shape2 = shapeFactory.getShape("RECTANGLE");shape2.draw();Shape shape3 = shapeFactory.getShape("SQUARE");shape3.draw();}
}