工厂模式提供了创建对象的最佳方式,创建对象时不会向客户端暴露创建逻辑,并且通过一个共同的接口指向新创建的对象。
1、创建一个接口
public interface Shape { void draw(); }
2、具体的对象
public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
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."); } }
3、定义工厂类
public class ShapeFactory { public Shape getShape(String shapeType) { if (null == shapeType) { return null; } switch (shapeType) { case "CIRCLE": return new Circle(); case "RECTANGLE": return new Rectangle(); case "SQUARE": return new Square(); default: return null; } } }
4、测试
public class _Test { public static void main(String[] args) { ShapeFactory factory = new ShapeFactory(); Shape shape1 = factory.getShape("CIRCLE"); shape1.draw(); Shape shape2 = factory.getShape("RECTANGLE"); shape2.draw(); Shape shape3 = factory.getShape("SQUARE"); shape3.draw(); } }