Design patterns

Design patterns 是程式設計中常見問題的典型解決套路,適當使用可以加強程式可擴展性和可延續性。可分為三類:

Creational

Creational design patterns 泛指在創造物件上的方法

Singleton

Singleton 的概念是讓一個 Class 只能被 Instantiate 一次。這可以用在不可以有兩個 instance 的物件上(例如機器底盤不可能會有兩個)。

Singleton in c++:

#include <iostream>
using namespace std;

class Chassis {
    private:
        // pointer storing the only instance
        static Chassis* instance; 
        
        // new constructor
        Chassis() {}
        
    public:
        // delete default constructor
        Chassis(const Chassis& obj) = delete;
        
        // get the only instance
        static Chassis* get_instance() {
            if (instance == nullptr) {
                instance = new Chassis();
            }
            return instance;
        }
};

Chassis* Chassis::instance = NULL;

int main() {
    Chassis* c = Chassis::get_instance();
    Chassis* d = Chassis::get_instance();

    // addresses for the first and second instance are equal
    std::cout << c << std::endl;
    std::cout << d << std::endl; 
    return 0;
}

Factory

Factory 的概念是透過一個 Class 進行生成。這個 Class 就像一個工廠一樣,基於輸入創造不同種類的物件

Factory in c++:

Builder

Builder 顧名思義,就像建築師一樣一步一步的蓋房子,是創造複雜物件的其中一種方式

Structural

Structural design patterns 泛指物件互相使用和架構的方式

Facade

Facade 的概念是用一個 Super class 創造一個整潔的使用者介面。使用這個物件的人不需要知道其內容並單一操控,只需要使用 Super class 的大功能即可

Composite

Composite 的概念是把物件包含的子物件組合成樹狀結構並加以處理那些子物件

Behavioral

Structural design patterns 泛指物件互相溝通的特殊方式

Iterator

Iterator 可讓您在不暴露其底層的情況下遍歷 array 的元件

更多 design patterns: https://refactoring.guru/design-patterns/catalog

Last updated