Java设计模式教程 - Java设计模式 - 工厂模式

工厂模式是一种创建型模式,因为此模式提供更好的途径去创建对象。
在工厂模式里,我们不用向客户端暴露创建逻辑而能创建对象。
例子
下面展示如何使用工厂模式去创建对象。
该工厂模式将创建形状的对象,比如圆、长方形。
首先我们设计一个表示形状(Shape)的接口。
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.");
   }
}

工厂模式的核心是工厂类。以下代码展示如何给Shape对象创建工厂类。
ShapeFactory类基于传入getShape()方法的字符串类型而创建Shape对象。如果字符串值是CIRCLE,它就创建一个Circle对象。
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;
   }
}

以下代码包含main方法,而它通过传递形状的type信息而使用工厂类去取得具体类的对象。
public class Main {

   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();
   }
}

以上代码生成以下结果。

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

猜你喜欢

转载自jonathan-chen.iteye.com/blog/2194074