工厂设计模式是一种创建型的设计模式,用于创建对象。屏蔽了下层对象的创建过程。
需要一个接口对象,一个创建对象的工厂。
一个接口对象
public interface Shape { void draw(); }
public class Circle implements Shape { @Override public void draw(){ System.out.println("circle draw"); } }
public class Rectangle implements Shape{ @Override public void draw(){ System.out.println("Rectangle draw"); } }
public class Square implements Shape { public void draw(){ System.out.println("square draw"); } }
public class ShapeFactory { //使用 getShape 方法获取形状类型的对象 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; } }
public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //获取 Circle 的对象,并调用它的 draw 方法 Shape shape1 = shapeFactory.getShape("CIRCLE"); //调用 Circle 的 draw 方法 shape1.draw(); //获取 Rectangle 的对象,并调用它的 draw 方法 Shape shape2 = shapeFactory.getShape("RECTANGLE"); //调用 Rectangle 的 draw 方法 shape2.draw(); //获取 Square 的对象,并调用它的 draw 方法 Shape shape3 = shapeFactory.getShape("SQUARE"); //调用 Square 的 draw 方法 shape3.draw(); } }
工厂设计模式体现的是java的面相接口编程的思想,使用工厂产生对象。
容易扩展。