工廠(chǎng)模式分為三種:
1. 簡(jiǎn)單工廠(chǎng)
特點(diǎn):一個(gè)工廠(chǎng)類(lèi)根據(jù)傳入的參量決定創(chuàng)建出那一種產(chǎn)品類(lèi)的實(shí)例搅吁,如果想要增加一個(gè)產(chǎn)品,需要修改工廠(chǎng)類(lèi),該設(shè)計(jì)破壞了開(kāi)閉原則椿息。
public interface Fruit {
}
public class Apple implements Fruit {
}
public class Orange implements Fruit {
}
public class SimpleFactory {
public static Fruit createFruit(String name){
if("apple".equals(name)){
return new Apple();
}else if("orange".equals(name)){
return new Orange();
}else{
throw new RuntimeException("unknown fruit name");
}
}
}
public class T {
public static void main(String[] args) {
Fruit apple = SimpleFactory.createFruit("apple");
}
}
2. 工廠(chǎng)方法
特點(diǎn):定義一個(gè)用于創(chuàng)建產(chǎn)品的接口法希,由子類(lèi)決定生產(chǎn)什么產(chǎn)品枷餐。每個(gè)產(chǎn)品都對(duì)應(yīng)了一個(gè)創(chuàng)建者,每個(gè)創(chuàng)建者獨(dú)立負(fù)責(zé)創(chuàng)建對(duì)應(yīng)的產(chǎn)品對(duì)象苫亦,非常符合單一職責(zé)原則毛肋。但是每增加一個(gè)產(chǎn)品都需要增加一個(gè)對(duì)應(yīng)的工廠(chǎng)實(shí)現(xiàn)怨咪,增加了系統(tǒng)的復(fù)雜性
public interface Fruit {
}
public class Apple implements Fruit {
}
public class Orange implements Fruit {
}
public interface FruitFactory {
Fruit createFruit();
}
public class AppleFactory implements FruitFactory {
@Override
public Fruit createFruit() {
return new Apple();
}
}
public class OrangeFactory implements FruitFactory {
@Override
public Fruit createFruit() {
return new Orange();
}
}
public class T {
public static void main(String[] args) {
FruitFactory appleFactory = new AppleFactory();
Fruit apple = appleFactory.createFruit();
FruitFactory orangeFactory = new OrangeFactory();
Fruit orange = orangeFactory.createFruit();
}
}
3. 抽象工廠(chǎng)
特點(diǎn):提供一個(gè)創(chuàng)建產(chǎn)品族的接口,其每個(gè)子類(lèi)可以生產(chǎn)一系列相關(guān)的產(chǎn)品润匙。創(chuàng)建相關(guān)或依賴(lài)對(duì)象的家族诗眨,而無(wú)需明確指定具體類(lèi),但是在新增一個(gè)產(chǎn)品時(shí)孕讳,需要修改工廠(chǎng)接口及其子類(lèi)匠楚,破壞了開(kāi)閉原則
public interface Staple {
}
public class Flour implements Staple {
}
public class Rice implements Staple {
}
public interface Dish {
}
public class Cabbage implements Dish {
}
public class Radish implements Dish{
}
public interface FoodFactory {
Staple createStaple();
Dish createDish();
}
public class NorthFood implements FoodFactory {
@Override
public Staple createStaple() {
return new Flour();
}
@Override
public Dish createDish() {
return new Radish();
}
}
public class SouthFood implements FoodFactory {
@Override
public Staple createStaple() {
return new Rice();
}
@Override
public Dish createDish() {
return new Cabbage();
}
}
public class T {
public static void main(String[] args) {
FoodFactory southFoodFactory = new SouthFood();
Dish cabbage = southFoodFactory.createDish();
Staple rice = southFoodFactory.createStaple();
FoodFactory norFoodFactory = new NorthFood();
Dish rasidh = southFoodFactory.createDish();
Staple flour = southFoodFactory.createStaple();
}
}