目的:通過工廠來產(chǎn)生對(duì)象。
使用場(chǎng)景:當(dāng)需要?jiǎng)?chuàng)建很多對(duì)象,這樣如果需要修改對(duì)象,我們就可以直接修改這個(gè)工廠類;或者創(chuàng)建復(fù)雜對(duì)象時(shí)考慮使用。
分類:簡(jiǎn)單工廠模式、普通工廠模式、抽象工廠模式;
1.簡(jiǎn)單工廠模式
優(yōu)點(diǎn):結(jié)構(gòu)簡(jiǎn)單,代碼量少;
缺點(diǎn):不符合開閉原則,每次添加產(chǎn)品都要修改StaticFactory這個(gè)類;

interface Product{}
class ProductA implements Product{}
class ProductB implements Product{}
class ProductC implements Product{}
public class StaticFactory {
private StaticFactory(){}
????public static Product getA(){? return new ProductA(); }
????public static Product getB(){? return new ProductB(); }
????public static Product?getC(){? return new ProductC(); }
}
class Client{
????//客戶端代碼只需要將相應(yīng)的參數(shù)傳入即可得到對(duì)象
????//用戶不需要了解工廠類內(nèi)部的邏輯。
????public void get(String name){
????????Product?x = null ;
????????if ( name.equals("A")) {
????????????x = StaticFactory.getProductA();
????????}else if ( name.equals("B")){
????????????x = StaticFactory.getProductB();
????????}else {
????????????x = StaticFactory.getProductC();
????????}
????}
}
2.普通工廠模式
優(yōu)點(diǎn):由于簡(jiǎn)單工廠違背了開放封閉原則;
缺點(diǎn):每次添加一個(gè)產(chǎn)品都要添加對(duì)應(yīng)的工廠類,增加了代碼量;

public interface Factory {
????Product createProduct();
}
生產(chǎn)ProductA的工廠FactoryA
public class FactoryA implements Factory?{
????@Override
????public Product createProduct() {
????????return new ProductA();
????}
}
生產(chǎn)ProductB的工廠FactoryB
public class FactoryB implements Factory?{
????@Override
????public Product createProduct() {
????????return new ProductB();
????}
}
同樣地,生產(chǎn)ProductC的工廠FactoryC跟以上模式一樣。
現(xiàn)在來根據(jù)新的工廠方法模式來生產(chǎn)
class Client{
????//客戶端代碼只需要將相應(yīng)的參數(shù)傳入即可得到對(duì)象
????//用戶不需要了解工廠類內(nèi)部的邏輯。
????public void get(String name){
????????Factory?x = null ;
????????if ( name.equals("A")) {
????????????x = new FactoryA.createProduct();
????????}else if ( name.equals("B")){
????????????x = new FactoryB.createProduct();
????????}else {
????????????x = new FactoryC.createProduct();
????????}
????}
}
3.抽象工廠模式
(1)通過反射實(shí)現(xiàn)的抽象工廠
普通工廠模式:一個(gè)具體的工廠類只生產(chǎn)一個(gè)具體的產(chǎn)品;
抽象工廠模式:一個(gè)具體的工廠類負(fù)責(zé)生產(chǎn)多個(gè)具體的產(chǎn)品;
優(yōu)點(diǎn):在普通工廠模式中,由于我們每添加一個(gè)產(chǎn)品都要添加對(duì)應(yīng)的工廠模式,所以提出抽象工廠模式,這樣就可以只存在一個(gè)抽象工廠類;
缺點(diǎn):需要反射支持;

class AbstractFactory implements Factory{
????private reflect ref;
????public Product createProduct(class name){
????????//通過反射
????????return ref.instance(name);
????}
}
(2)不通過反射實(shí)現(xiàn)的抽象工廠模式

4.工廠的模板類
? ??struct Factory {
????????????template<typename T, typename ...Args>
????????????static std::unique_ptr CreateObj(Args ...args)
? ? ????????{
? ? ? ? ????????????????return std::make_unique(std::forward<Args>(args)...);
? ? ????????}
};