簡單工廠模式
1. 目的
工廠模式就是專門負責將大量有共同接口的類實例化,而且不必事先知道每次是要實例化哪一個類的模式。它定義一個用於創建對象的接口,由子類決定實例化哪一個類。
2 . 簡單工廠模式的結構
- // 產品接口
- public interface Product {
- public void getName();
- }
- // 具體產品A
- public class ProductA implements Product {
- public void getName() {
- System.out.println(" I am ProductA ");
- }
- }
- // 具體產品B
- public class ProductB implements Product {
- public void getName() {
- System.out.println(" I am ProductB ");
- }
- }
- // 工廠類
- public class ProductCreator {
- public Product createProduct(String type) {
- if (" A ".equals(type)) {
- return new ProductA();
- }
- if (" B ".equals(type)) {
- return new ProductB();
- } else
- return null;
- }
- public static void main(String[] args) {
- ProductCreator creator = new ProductCreator();
- creator.createProduct(" A ").getName();
- creator.createProduct(" B ").getName();
- }
- }
• 在編碼時不能預見需要創建哪一種類的實例。
• 一個類使用它的子類來創建對象。
• 開發人員不希望創建了哪個類的實例以及如何創建實例的信息暴露給外部程序。
抽象工廠模式
1. 抽象工廠模式可以說是簡單工廠模式的擴展,它們主要的區別在於需要創建對象的複雜程度上。
在抽象工廠模式中,抽象產品可能是一個或多個,從而構成一個或多個產品族。 在只有一個產品族的情況下,抽象工廠模式實際上退化到工廠方法模式。
2. 抽象工廠模式的結構
3. 一個簡單例子
- // 產品 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();
- }
- }
在以下情況下,應當考慮使用抽象工廠模式。
首先,一個系統應當不依賴於產品類實例被創立,組成,和表示的細節。這對於所有形態的工廠模式都是重要的。
其次,這個系統的產品有多於一個的產品族。
第三,同屬於同一個產品族的產品是設計成在一起使用的。這一約束必須得在系統的設計中體現出來。
最後,不同的產品以一系列的接口的面貌出現,從而使系統不依賴於接口實現的細節。
其中第二丶第三個條件是我們選用抽象工廠模式而非其它形態的工廠模式的關鍵性條件。