創作不易,本篇文章如果幫助到了你,還請點贊 關注支持一下?>𖥦<)!!
主頁專欄有更多知識,如有疑問歡迎大家指正討論,共同進步!
🔥c++系列專欄:C/C++零基礎到精通 🔥給大家跳段街舞感謝支持!? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
c語言內容💖:
專欄:c語言之路重點知識整合
【c語言】全部知識點總結
目錄
- 一、工廠模式的特點
- 二、簡單工廠模式(靜態工廠)
- 三、工廠方法
- 四、抽象工廠
一、工廠模式的特點
工廠模式提供了一種封裝對象創建過程的方式,使得代碼更易于管理和擴展。
工廠模式隱藏了對象的具體創建過程,從而可以通過接口來創建對象,而無需關心具體的實現細節。
擴展性高:工廠模式利于后期方法的維護,解耦合。
二、簡單工廠模式(靜態工廠)
將對象的創建和使用分離,由一個工廠類根據傳入的參數來決定創建哪一種產品類的實例
#include <iostream>
using namespace std;class Product
{//抽象類
public:virtual void use() = 0; // 純虛函數,定義產品接口
};class ProductA : public Product {
public:void use() override {cout << "ProductA::use()" << endl;}
};class ProductB : public Product {
public:void use() override {cout << "ProductB::use()" << endl;}
};class SimpleFactory
{//簡單工廠
public:static Product* createProduct(const string& type) {//根據傳入的參數來決定創建哪一種產品類的實例if (type == "A") {cout << "create ProductA" << endl;return new ProductA();}else if (type == "B") {cout << "create ProductB" << endl;return new ProductB();}return nullptr;}
};int main()
{//根據產品類型創建產品Product* product = SimpleFactory::createProduct("B");//使用對應類型的產品if (product){product->use();delete product; }return 0;
};
三、工廠方法
簡單工廠違背了開閉原則,故將簡單工廠中的工廠拆分為多個工廠:
增加產品時 Factory 工廠不用改變,只需要添加對應產品類型的工廠
#include <iostream>
using namespace std;class Product {
public:virtual void use() = 0;
};class ProductA : public Product {
public:void use() override { cout << "ProductA::use()" << endl; }
};class ProductB : public Product {
public:void use() override { cout << "ProductB::use()" << endl; }
};//工廠方法
class Creator
{//抽象類 工廠方法
public:virtual Product* createProduct() = 0;
};class CreatorA : public Creator
{//ProductA工廠
public:Product* createProduct() override {cout << "CreatorA createProduct ProductA" << endl;return new ProductA();}
};class CreatorB : public Creator
{//ProductB工廠
public:Product* createProduct() override {cout << "CreatorB createProduct ProductB" << endl;return new ProductB();}
};int main()
{//創建工廠:生產A產品類型的工廠Creator* creator = new CreatorA();//使用該工廠創建產品Product* product = creator->createProduct();//使用產品product->use();delete product; // 釋放產品 delete creator; // 釋放工廠return 0;
};
四、抽象工廠
抽象工廠與工廠方法類似,工廠不止用來生產一種產品,可以用于創建與產品相關的一系列產品
適用于大批量、一系列的對象的生產。
大家的點贊、收藏、關注將是我更新的最大動力! 歡迎留言或私信建議或問題。 |
大家的支持和反饋對我來說意義重大,我會繼續不斷努力提供有價值的內容!如果本文哪里有錯誤的地方還請大家多多指出(●'?'●) |