Java设计模式之——工厂模式

工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

工厂模式的 UML 图

步骤 1

创建一个接口。

1 Package com.demo.mode.mode01.factory.Shape.java
2 
3 public interface Shape {
4 
5   void draw();
6 
7 }

步骤 2

创建实现接口的实体类。

Package com.demo.mode.mode01.factory.Rectangle.java

public class Rectangle implements Shape {

  public void draw() {

System.out.println("executeRectangle::draw() method.");

  }

}

Package com.demo.mode.mode01.factory.Square.java

public class Square implements Shape {

  public void draw() {

     System.out.println("execute Square::draw()method.");

  }

}

Package com.demo.mode.mode01.factory.Circle.java

public class Circle implements Shape {

  public void draw() {

     System.out.println("execute Circle::draw()method.");

  }

}

步骤 3

创建一个工厂,生成基于给定信息的实体类的对象。

Package com.demo.mode.mode01.factory.ShapeFactory.java

public class ShapeFactory {

  /**

   * 使用 getShape 方法获取形状类型的对象

   * @author xg.qiu<br/>

   * @since JDK 1.7

   * @time Jul 28, 2015

   * @param shapeType 形状类型

   * @return shape对象

   */

  public static Shape getShape(String shapeType) {

     // shape对象

     Shape shape = null;

  if ("Circle".equals(shapeType)) {

       shape = new Circle();

} else if ("Rectangle".equals(shapeType)) {

       shape = new Rectangle();

     } else if ("Square".equals(shapeType)) {

       shape = new Square();

     }

     return shape;

  }

}

步骤 4

使用该工厂,通过传递类型信息来获取实体类的对象。

Package com.demo.mode.mode01.factory.FactoryPatternDemo.java

public class FactoryPatternDemo {

  public static void main(String[] args) {

     //1.画圆Circle

     Shape shapeCircle = ShapeFactory.getShape("Circle");

     shapeCircle.draw();

     //2.画长方形Rectangle

     Shape shapeRectangle = ShapeFactory.getShape("Rectangle");

     shapeRectangle.draw();

     //3.画正方形Square

     Shape shapeSquare = ShapeFactory.getShape("Square");

     shapeSquare.draw();

  }

}

步骤 5

验证输出。

execute Circle::draw() method.

execute Rectangle::draw() method.

execute Square::draw() method. 

 

原文地址:https://www.cnblogs.com/XQiu/p/5086320.html