DesignPatterns/c++/abstract_factory.cc
2025-07-10 22:26:33 +08:00

38 lines
816 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @name 抽象工厂模式
* @brief: 创建相关对象族
* @note 场景跨平台UI组件库如 Windows/macOS 按钮+文本框组合)
*/
class Button {
public:
virtual void render() = 0;
};
class WinButton : public Button {
public:
void render() override {}
};
class MacButton : public Button {
public:
void render() override {}
};
class GUIFactory {
public:
virtual Button* createButton() = 0;
};
class WinFactory : public GUIFactory {
Button* createButton() override { return new WinButton(); }
};
class MacFactory : public GUIFactory {
Button* createButton() override { return new MacButton(); }
};
int main()
{
// 使用
GUIFactory* factory = new WinFactory(); // 根据配置切换
Button* btn = factory->createButton();
btn->render();
return 0;
}