C++中常见的面向对象设计模式

美食旅行家 2022-05-03 ⋅ 15 阅读

设计模式是一套解决问题的可复用方案,它能提高代码的可读性、可维护性和可扩展性。在这篇博客中,我将介绍一些常见的面向对象设计模式,帮助读者在C++中编写更高效、可靠的代码。

1. 工厂模式(Factory Pattern)

工厂模式用于创建对象,而不暴露对象的创建逻辑。它是一种创建型模式,通过使用工厂类来实现对象的实例化,并返回创建的对象。

class Shape {
public:
    virtual void draw() = 0;
};

class Circle : public Shape {
public:
    void draw() {
        cout << "Drawing Circle" << endl;
    }
};

class Square : public Shape {
public:
    void draw() {
        cout << "Drawing Square" << endl;
    }
};

class ShapeFactory {
public:
    static Shape* createShape(string type) {
        if (type == "Circle") {
            return new Circle();
        } else if (type == "Square") {
            return new Square();
        }
        return nullptr;
    }
};

int main() {
    Shape* circle = ShapeFactory::createShape("Circle");
    circle->draw();  // Drawing Circle

    Shape* square = ShapeFactory::createShape("Square");
    square->draw();  // Drawing Square

    delete circle;
    delete square;
}

2. 单例模式(Singleton Pattern)

单例模式确保一个类只有一个实例,并提供全局访问点。它是一种创建型模式,通常用于共享资源的管理和控制。

class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }

    void doSomething() {
        cout << "Doing something" << endl;
    }
};

Singleton* Singleton::instance = nullptr;

int main() {
    Singleton* s1 = Singleton::getInstance();
    s1->doSomething();

    Singleton* s2 = Singleton::getInstance();
    s2->doSomething();

    // s1 和 s2 是同一对象,返回 true
    cout << (s1 == s2) << endl;

    delete s1;
    delete s2;
}

3. 观察者模式(Observer Pattern)

观察者模式定义了对象之间的一对多依赖关系,当一个对象的状态改变时,它的所有依赖者都会收到通知并自动更新。

class Observer {
public:
    virtual void update(int value) = 0;
};

class Subject {
private:
    vector<Observer*> observers;
    int value;

public:
    void attach(Observer* observer) {
        observers.push_back(observer);
    }

    void setValue(int newValue) {
        value = newValue;
        notify();
    }

    void notify() {
        for (auto o : observers) {
            o->update(value);
        }
    }
};

class ConcreteObserver : public Observer {
public:
    void update(int value) {
        cout << "New value is " << value << endl;
    }
};

int main() {
    Subject subject;
    ConcreteObserver observer1;
    ConcreteObserver observer2;

    subject.attach(&observer1);
    subject.attach(&observer2);

    subject.setValue(10);
    // 输出:
    // New value is 10
    // New value is 10

    subject.setValue(20);
    // 输出:
    // New value is 20
    // New value is 20
}

4. 策略模式(Strategy Pattern)

策略模式定义了一个抽象的策略类,将算法的选择和使用与算法的具体实现分离开来。

class Strategy {
public:
    virtual double calculate(double a, double b) = 0;
};

class AddStrategy : public Strategy {
public:
    double calculate(double a, double b) {
        return a + b;
    }
};

class SubtractStrategy : public Strategy {
public:
    double calculate(double a, double b) {
        return a - b;
    }
};

class Calculator {
private:
    Strategy* strategy;

public:
    void setStrategy(Strategy* newStrategy) {
        strategy = newStrategy;
    }

    double executeStrategy(double a, double b) {
        return strategy->calculate(a, b);
    }
};

int main() {
    Calculator calculator;
    AddStrategy add;
    SubtractStrategy subtract;

    calculator.setStrategy(&add);
    cout << calculator.executeStrategy(5, 3) << endl;  // 输出: 8

    calculator.setStrategy(&subtract);
    cout << calculator.executeStrategy(5, 3) << endl;  // 输出: 2
}

以上是一些C++中常见的面向对象设计模式。使用这些设计模式可以提高代码的可复用性和可维护性,帮助开发者编写高质量的代码。希望这篇博客能对你有所帮助!


全部评论: 0

    我有话说: