爱程序网

Java的工厂模式简介

来源: 阅读:

工厂模式主要是为创建对象提供过渡接口,以便将创建对象的具体过程屏蔽隔离起来,达到提高灵活性的目的。

在下面的章节中,我们将展示如何使用工厂模式来创建对象。

由工厂模式创建的对象将是形状的物体,如圆形,矩形。

首先,我们设计代表形状的接口。

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 Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}

 

Circle.java

public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}

 

核心工厂模式是工厂类。下面的代码演示如何创建一个工厂类Shape对象。

该ShapeFactory类创建基于传递到getShape()方法的字符串值Shape对象。如果字符串值是圆,它会创建一个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;
   }
}

 

下面的代码有mian方法,它采用工厂类传递一个信息,如类型,以获得具体类的对象。

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

 

原文地址:http://www.manongjc.com/article/135.html

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助