#include<iostream>
// 抽象产品接口
class Button {
public:
virtual void render() = 0;
};
// 具体产品类A
class WindowsButton : public Button {
public:
void render() override {
std::cout << "Rendering a Windows button." << std::endl;
}
};
// 具体产品类B
class MacButton : public Button {
public:
void render() override {
std::cout << "Rendering a Mac button." << std::endl;
}
};
// 抽象工厂接口
class GUIFactory {
public:
virtual Button* createButton() = 0;
};
// 具体工厂类A
class WindowsFactory : public GUIFactory {
public:
Button* createButton() override {
return new WindowsButton();
}
};
// 具体工厂类B
class MacFactory : public GUIFactory {
public:
Button* createButton() override {
return new MacButton();
}
};
int main()
{
//创建一个Windows风格的工厂
GUIFactory* windowsFactory = new WindowsFactory();
//创建一个Windows风格的按钮
Button* windowsButton = windowsFactory->createButton();
//渲染按钮
windowsButton->render(); //Output:Rendering a Windows button.
//创建一个Mac风格的工厂
GUIFactory* macFactory = new MacFactory();
//创建一个Mac风格的按钮
Button* macButton = macFactory->createButton();
//渲染按钮
macButton->render(); //Output:Rendering a Mac button.
delete windowsFactory;
delete windowsButton;
delete macFactory;
delete macButton;
return 0;
}
抽象工厂模式(c++)
最新推荐文章于 2024-09-05 16:20:01 发布