引言
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance; // 静态局部变量确保只初始化一次
return instance;
}
// ...其他成员函数和变量...
private:
Singleton() {} // 私有构造函数,防止外部创建实例
};
class Shape { public: virtual void draw() = 0; };
class Circle : public Shape { public: void draw() override { /*...*/ } };
class Rectangle : public Shape { public: void draw() override { /*...*/ } };
Shape* createShape(const std::string& type) {
if (type == "circle") return new Circle();
if (type == "rectangle") return new Rectangle();
return nullptr; // 错误处理...
}
template<typename T>
class Observer {
public:
virtual void update(T& subject) = 0;
};
template<typename T>
class Subject {
public:
void registerObserver(Observer<T>* observer) { /*...*/ }
void removeObserver(Observer<T>* observer) { /*...*/ }
void notifyObservers() { /*...*/ }
};
class Component { public: virtual void operation() = 0; };
class Decorator : public Component { public: Decorator(Component* component) { /*...*/ } };