設計模式 工廠模式

2021-07-04 06:58:24 字數 2548 閱讀 8700

工廠模式:

- 實現了建立者和呼叫者的分離,例項化物件,用工廠方法代替new操作。將選擇實現類、建立物件統一管理和控制。從而將呼叫者跟我們的實現類解耦。

- 詳細分類:

1、簡單工廠模式

用來生產同一等級結構中的任意產品。(對於增加新的產品,需要修改已有的**)

2、工廠方法模式

用來生產同一等級結構中的固定產品。(支援增加任意產品)

3、抽象工廠模式

用來生產不同產品族的全部產品。(對於增加新的產品,無能為力;支援增加產品族)

一、簡單工廠模式的實現

要點:1、簡單工廠模式也叫靜態工廠模式,就是工廠類一般是使用靜態方法,通過接收的引數的不同來返回不同的物件例項。

2、對於增加新產品無能為力(必須需要工廠方法)!不修改**的話,是無法擴充套件的。

public inte***ce car 

public class audi implements car

}public class benz implements car

}public class car******factory else if("賓士".equals(type))

return null; }}

/** * 簡單工廠模式下,呼叫者只需跟工廠打交道生產物件,而不需要跟具體實現類打交道

* @author administrator

* */

public class client

}

簡單工廠模式的類圖如下:

二、工廠方法模式的實現

要點:1、工廠方法模式和簡單工廠模式的不同在於,簡單工廠模式只有乙個工廠類,而工廠方法模式有一組實現了相同介面的工廠類。

public inte***ce car 

public inte***ce ca***ctory

public class audi implements car

}public class audifactory implements ca***ctory

}public class benz implements car

}public class benzfactory implements ca***ctory

}/**

* 工廠方法模式測試

*/public class client

}

工廠方法模式的類圖如下:

三、抽象工廠模式的實現

用來生產不同產品族的全部產品。

抽象工廠模式是工廠方法模式的公升級版本,在有多個業務品種、業務分類時,通過抽象工廠模式生產需要的物件是一種非常好的解決方式。

/**

* 發動機

*/public inte***ce engine

/** * 高階發動機

*/class luxuryengine implements engine

public void start() }

/** * 低端發動機

*/class lowengine implements engine

public void start() }

public inte***ce seat

/** * 高階座椅

*/class luxuryseat implements seat

}/**

* 低端座椅

*/class lowseat implements seat

}public inte***ce tyre

/** * 高階輪胎

*/class luxurytyre implements tyre

}/**

* 低端輪胎

*/class lowtyre implements tyre

}public inte***ce ca***ctory

/** * 低端汽車

*/public class lowca***ctory implements ca***ctory

public seat createsea()

public tyre createtyre()

}/**

* 高階汽車

*/public class luxuryca***ctory implements ca***ctory

public seat createsea()

public tyre createtyre()

}public class client

}

抽象工廠模式的類圖:

設計模式 工廠模式 抽象工廠模式

建立物件時不會對客戶暴露建立邏輯,並且通過使用乙個共同的介面來指向建立的物件。sept1 建立乙個公共介面,將要對外開放的方法在這裡定義。sept2 建立實現介面的類,用即實現對外開放的類的方法 sept3 建立工廠,提供乙個get方法,這個方法提供返回實現類的物件 建立選擇 sept4 使用,建立...

設計模式 工廠設計模式

用於建立物件的介面,交給子類去實現 我們舉乙個生產nokia的例子 public abstract class nokiaphone先試定義了乙個抽象類,抽象出方法poweronphone 模擬手機開機的動作 public class nokia5200 extends nokiaphone pub...

設計模式 工廠設計模式

工廠模式分為工廠方法模式和抽象工廠模式 工廠方法模式分為 普通工廠模式,就是建立乙個工廠類,對實現了同一介面的一些類進行例項的建立。多個工廠方法模式,是對普通工廠方法模式的改進,在普通工廠方法模式中,如果傳遞的字串出錯,則不能正確建立物件,而多個工廠方法模式是提供多個工廠方法,分別建立物件。靜態工廠...