工廠模式只適用於對象的創建。說白了就是封裝了new‘一個對象的操作。
簡單工廠模式
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. 抽象工廠模式可以說是簡單工廠模式的擴展,
它們主要的區別在於需要創建對象的複雜程度上。
在抽象工廠模式中,創建對象的方法變成了接口(對應與c++的虛函數),可以讓具體的創建對象的子類來實現。
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();
- }
- }