单例模式
template<typename T>
T& singleton() {
static T inst;
return inst;
}
模板模式
算法整体流程固定,但每个步骤的实现细节可能不同时,可以将每个步骤设计为虚函数,将这些步骤组合起来作为一个“模板”。
class Character {
protected:
virtual void move();
virtual void draw();
public:
//模板
void update() {
move();
move();
draw();
}
};
class Game {
private:
vector<Character> chars;
public:
void update() {
for (auto& c : chars) {
c.update();
}
}
};
原型模式
struct Ball {
virtual unique_ptr<Ball> clone() = 0;
};
template<typename T>
struct BallImpl : Ball {
unique_ptr<Ball> clone() override {
T* that = static_cast<T*>(this);
return make_unique<T>(*that);
}
};
struct RedBall : BallImpl<RedBall> {
// 自动实现了clone函数
};
struct BlueBall : BallImpl<BlueBall> {
// 自动实现了clone函数
};