工场模式:通过一个公共接口来将 对象的创建逻辑与用户分离。
例子:
创建一个ShapeFactory获得不同的Shape对象(Circle,Rectangle,Square)
第一步:创建接口Shape.java
public interface Shape { void draw(); }
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
public class Circle implements Shape{ @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
第三步:创建工场类ShapeFactory.java,根据用户传入的信息获得对应的类的实例
public class ShapeFactory { public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } }
第四步:使用工场类测试 FactoryPatternDemo.java
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(); } }
输出结果:
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.