Abstract Factory(抽象工廠模式) _after

本文通过一个具体的工厂模式实现示例,展示了如何根据不同条件创建不同类型的界面组件,如按钮和菜单等,并通过预编译指令实现了运行时的选择。
# include <iostream>
using namespace std; 

#define WINDOWS

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

class MotifButton : public Widget {
public:
   
void draw() { cout << "MotifButton\n"; }
};
class MotifMenu : public Widget {
public:
   
void draw() { cout << "MotifMenu\n"; }
};

class WindowsButton : public Widget {
public:
   
void draw() { cout << "WindowsButton\n"; }
};
class WindowsMenu : public Widget {
public:
   
void draw() { cout << "WindowsMenu\n"; }
};

class Factory {
public:
   
virtual Widget* create_button() = 0;
   
virtual Widget* create_menu() = 0;
};

class MotifFactory : public Factory {
public:
   Widget
* create_button() {
      
return new MotifButton; }
   Widget
* create_menu()   {
      
return new MotifMenu; }
};

class WindowsFactory : public Factory {
public:
   Widget
* create_button() {
      
return new WindowsButton; }
   Widget
* create_menu()   {
      
return new WindowsMenu; }
};

Factory
* factory;

void display_window_one() {
   Widget
* w[] = { factory->create_button(),
                   factory
->create_menu() };
   w[
0]->draw();  w[1]->draw();
}

void display_window_two() {
   Widget
* w[] = { factory->create_menu(),
                   factory
->create_button() };
   w[
0]->draw();  w[1]->draw();
}

int main( void ) {
#ifdef MOTIF
   factory 
= new MotifFactory;
#else // WINDOWS
   factory 
= new WindowsFactory;
#endif

   Widget
* w = factory->create_button();
   w
->draw();
   display_window_one();
   display_window_two();
}

// WindowsButton
// WindowsButton
// WindowsMenu
// WindowsMenu
// WindowsButton

转载于:https://www.cnblogs.com/jerry550409/archive/2009/02/19/1393572.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值