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();}
}