工廠(chǎng)模式

純粹學(xué)習(xí)筆記。

  • 工廠(chǎng)模式

我們?cè)趧?chuàng)建對(duì)象時(shí),不向客戶(hù)端暴露創(chuàng)建邏輯。主要解決接口選擇的問(wèn)題。
實(shí)現(xiàn):創(chuàng)建一個(gè)shape接口和實(shí)現(xiàn)shape接口的實(shí)體類(lèi)。



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

創(chuàng)建一個(gè)工廠(chǎng),生成基于給定信息的實(shí)體類(lèi)的對(duì)象。
ShapeFactory.java

public class ShapeFactory {
   //使用 getShape 方法獲取形狀類(lèi)型的對(duì)象
   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;
   }
}

FactoryPatternDemo.java

public class FactoryPatternDemo {
 
   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();
 
      //獲取 Circle 的對(duì)象,并調(diào)用它的 draw 方法
      Shape shape1 = shapeFactory.getShape("CIRCLE");
 
      //調(diào)用 Circle 的 draw 方法
      shape1.draw();
 
      //獲取 Rectangle 的對(duì)象,并調(diào)用它的 draw 方法
      Shape shape2 = shapeFactory.getShape("RECTANGLE");
 
      //調(diào)用 Rectangle 的 draw 方法
      shape2.draw();
 
      //獲取 Square 的對(duì)象,并調(diào)用它的 draw 方法
      Shape shape3 = shapeFactory.getShape("SQUARE");
 
      //調(diào)用 Square 的 draw 方法
      shape3.draw();
   }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn):http://www.runoob.com/design-pattern/factory-pattern.ht...
    right_33cb閱讀 171評(píng)論 0 0
  • 轉(zhuǎn):http://www.runoob.com/design-pattern/abstract-factory-p...
    right_33cb閱讀 221評(píng)論 0 0
  • 意圖: 定義一個(gè)創(chuàng)建對(duì)象的接口,讓其子類(lèi)自己決定實(shí)例化哪一個(gè)工廠(chǎng)類(lèi),工廠(chǎng)模式使其創(chuàng)建過(guò)程延遲到子類(lèi)進(jìn)行 主要解決:...
    W有來(lái)有去閱讀 232評(píng)論 0 0
  • 簡(jiǎn)單工廠(chǎng)模式又叫靜態(tài)工廠(chǎng)模式,是工廠(chǎng)模式三中狀態(tài)中結(jié)構(gòu)最為簡(jiǎn)單的。主要有一個(gè)靜態(tài)方法,用來(lái)接受參數(shù),并根據(jù)參數(shù)來(lái)決...
    博為峰51Code教研組閱讀 306評(píng)論 0 0
  • 婚姻是什么,是不是所有的婚姻都會(huì)幸福呢,答案不是很肯定的,但,有一點(diǎn)至少可以肯定婚姻是一種合作關(guān)系,單靠一...
    鳥(niǎo)兒joyce7531閱讀 98評(píng)論 0 0

友情鏈接更多精彩內(nèi)容