5分钟理解设计模式之工厂模式

工厂模式是Java中最常用的设计模式。工厂模式提供很好的创建对象的方式,属于创建型模式。

使用工厂模式创建对象是不向使用者暴露创建细节,并且可以通过统一的接口引用对象。

实现

我们将创建Shape接口和实现Shape接口的具体类。下一步再声明工厂类ShapeFactory

示例类FactoryPatternDemo使用ShapeFactory获取Shape对象。通过给ShapeFactory传递图形参数(CIRCLE / RECTANGLE / SQUARE)来获取需要的对象。

 

第1步

创建一个接口

Shape.java

public interface Shape {
   void draw();
}

第2步

创建实现Shape接口的具体类

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.");
   }
}

第3步

创建工厂类,工厂类可以根据传入参数创建具体类的实例。

ShapeFactory.java

public class ShapeFactory {
    
   //use getShape method to get object of type shape 
   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;
   }
}

第4步

通过工厂类创建具体类的实例。

FactoryPatternDemo.java

public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of circle
      shape3.draw();
   }
}

第5步

验证输出

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

本文翻译自 http://www.tutorialspoint.com/design_pattern/factory_pattern.htm

(完)

posted on 2016-05-11 23:07  lima  阅读(1207)  评论(0编辑  收藏  举报

导航