其实简单工厂,在《Head First 设计模式》这本书里,并不是一个设计模式,而比较像一种编程习惯。另外个人认为,之所以说简单工厂并不是工厂模式,是因为工厂模式的精髓是“将创建延迟到子类进行”,简单工厂并没有体现这一点。
简单工厂特点:
把创建对象的代码提取了出来
创建的产品(工厂出产的产品)都依赖于抽象类
可能日常开发遇到的情形较多,因为比较简单,业务逻辑也简单。
类图:
一个形状类(父类或者接口)(包含一个draw方法):
public interface Shape { void draw(); }
子类(或实现)
Rectangle.java:
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
Square.java:
public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
Circle.java
public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
创建一个工厂类:
ShapeFactory.java
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(); } }
输出如下:
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.