Java 工廠模式

2023-10-18 14:44 更新

Java設(shè)計模式 - 工廠模式


工廠模式是一種創(chuàng)建模式,因為此模式提供了更好的方法來創(chuàng)建對象。

在工廠模式中,我們創(chuàng)建對象而不將創(chuàng)建邏輯暴露給客戶端。

例子

在以下部分中,我們將展示如何使用工廠模式創(chuàng)建對象。

由工廠模式創(chuàng)建的對象將是形狀對象,如圓形,矩形。

首先,我們設(shè)計一個接口來表示Shape。

public interface Shape {
   void draw();
}

然后我們創(chuàng)建實現(xiàn)接口的具體類。

以下代碼用于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.");
   }
}

核心工廠模式是一個Factory類。以下代碼顯示了如何為Shape對象創(chuàng)建Factory類。

ShapeFactory類基于傳遞給getShape()方法的String值創(chuàng)建Shape對象。如果String值為CIRCLE,它將創(chuàng)建一個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方法,并且它使用Factory類通過傳遞類型等信息來獲取具體類的對象。

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

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號