国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Java設計模式之工廠方法模式

2019-11-18 10:41:44
字體:
來源:轉載
供稿:網友
一 、工廠方法(Factory Method)模式

  工廠方法模式的意義是定義一個創建產品對象的工廠接口,將實際創建工作推遲到子類當中。核心工廠類不再負責產品的創建,這樣核心類成為一個抽象工廠角色,僅負責具體工廠子類必須實現的接口,這樣進一步抽象化的好處是使得工廠方法模式可以使系統在不修改具體工廠角色的情況下引進新的產品。

  二、 工廠方法模式角色與結構

  抽象工廠(Creator)角色:是工廠方法模式的核心,與應用程序無關。任何在模式中創建的對象的工廠類必須實現這個接口。

  具體工廠(Concrete Creator)角色:這是實現抽象工廠接口的具體工廠類,包含與應用程序密切相關的邏輯,并且受到應用程序調用以創建產品對象。在上圖中有兩個這樣的角色:BulbCreator與TubeCreator。

  抽象產品(PRodUCt)角色:工廠方法模式所創建的對象的超類型,也就是產品對象的共同父類或共同擁有的接口。在上圖中,這個角色是Light。

  具體產品(Concrete Product)角色:這個角色實現了抽象產品角色所定義的接口。某具體產品有專門的具體工廠創建,它們之間往往一一對應。
   
Java設計模式之工廠方法模式

  三、一個簡單的實例   

// 產品 Plant接口
public interface Plant { }
//具體產品PlantA,PlantB
public class PlantA implements Plant {

 public PlantA () {
  System.out.println("create PlantA !");
 }

 public void doSomething() {
  System.out.println(" PlantA do something ...");
 }
}
public class PlantB implements Plant {
 public PlantB () {
  System.out.println("create PlantB !");
 }

 public void doSomething() {
  System.out.println(" PlantB do something ...");
 }
}
// 產品 Fruit接口
public interface Fruit { }
//具體產品FruitA,FruitB
public class FruitA implements Fruit {
 public FruitA() {
  System.out.println("create FruitA !");
 }
 public void doSomething() {
  System.out.println(" FruitA do something ...");
 }
}
public class FruitB implements Fruit {
 public FruitB() {
  System.out.println("create FruitB !");
 }
 public void doSomething() {
  System.out.println(" FruitB do something ...");
 }
}
// 抽象工廠方法
public interface AbstractFactory {
 public Plant createPlant();
 public Fruit createFruit() ;
}
//具體工廠方法
public class FactoryA implements AbstractFactory {
 public Plant createPlant() {
  return new PlantA();
 }
 public Fruit createFruit() {
  return new FruitA();
 }
}
public class FactoryB implements AbstractFactory {
 public Plant createPlant() {
  return new PlantB();
 }
 public Fruit createFruit() {
  return new FruitB();
 }
}
  四、工廠方法模式與簡單工廠模式

  工廠方法模式與簡單工廠模式再結構上的不同不是很明顯。工廠方法類的核心是一個抽象工廠類,而簡單工廠模式把核心放在一個具體類上。

  工廠方法模式之所以有一個別名叫多態性工廠模式是因為具體工廠類都有共同的接口,或者有共同的抽象父類。

  當系統擴展需要添加新的產品對象時,僅僅需要添加一個具體對象以及一個具體工廠對象,原有工廠對象不需要進行任何修改,也不需要修改客戶端,很好的符合了"開放-封閉"原則。而簡單工廠模式在添加新產品對象后不得不修改工廠方法,擴展性不好。

  工廠方法模式退化后可以演變成簡單工廠模式。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 台中县| 修文县| 陵水| 岳西县| 札达县| 佛学| 霍城县| 南川市| 五常市| 重庆市| 同德县| 普陀区| 太原市| 江山市| 敦化市| 岢岚县| 中卫市| 东兴市| 勃利县| 上高县| 和政县| 五华县| 台北市| 遂宁市| 涿鹿县| 漠河县| 利辛县| 万山特区| 连云港市| 伽师县| 金乡县| 毕节市| 富蕴县| 麦盖提县| 喀什市| 峡江县| 罗定市| 祁阳县| 高碑店市| 拜泉县| 秭归县|