设计模式之工厂方法模式

1、定义了一个用于创建对象的接口,让子类决定实例化那一个类。工厂方法使一个类的实例化延迟到其子类。

UML图如下:


2、C++代码实现

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class LeiFeng  
  5. {  
  6. public:  
  7.     virtual void Sweep() {  
  8.         cout << "扫地" << endl;  
  9.     }  
  10.     virtual void Wash() {  
  11.         cout << "洗衣" << endl;  
  12.     }  
  13.     virtual void BuyRice() {  
  14.         cout << "买米" << endl;  
  15.     }  
  16. };  
  17.   
  18. class Undergraduate : public LeiFeng  
  19. {  
  20. public:  
  21.     void Sweep() {  
  22.         cout << "大学生";  
  23.         LeiFeng::Sweep();  
  24.     }  
  25.     void Wash() {  
  26.         cout << "大学生";  
  27.         LeiFeng::Wash();  
  28.     }  
  29.     void BuyRice() {  
  30.         cout << "大学生";  
  31.         LeiFeng::BuyRice();  
  32.     }  
  33. };  
  34.   
  35. class Volunteer : public LeiFeng  
  36. {  
  37. public:  
  38.     void Sweep() {  
  39.         cout << "志愿者";  
  40.         LeiFeng::Sweep();  
  41.     }  
  42.     void Wash() {  
  43.         cout << "志愿者";  
  44.         LeiFeng::Wash();  
  45.     }  
  46.     void BuyRice() {  
  47.         cout << "志愿者";  
  48.         LeiFeng::BuyRice();  
  49.     }  
  50. };  
  51.   
  52. //工厂抽象类  
  53. class Factory   
  54. {  
  55. public:  
  56.     virtual LeiFeng * CreateLeiFeng() = 0;  
  57. };  
  58.   
  59. //具体的大学生工厂  
  60. class UndergraduateFactory : public Factory  
  61. {  
  62. public:  
  63.     LeiFeng * CreateLeiFeng() {  
  64.         return new Undergraduate();  
  65.     }  
  66. };  
  67.   
  68. //具体的志愿者工厂  
  69. class VolunteerFactory : public Factory  
  70. {  
  71. public:  
  72.     LeiFeng * CreateLeiFeng() {  
  73.         return new Volunteer();  
  74.     }  
  75. };  
  76.   
  77. int main()  
  78. {  
  79.     Factory * p_factory = new UndergraduateFactory();  
  80.     LeiFeng * p_student = p_factory->CreateLeiFeng();  
  81.     p_student->Sweep();  
  82.     p_student->Wash();  
  83.     p_student->BuyRice();  
  84.   
  85.     delete p_factory;  
  86.     p_factory = NULL;  
  87.     p_factory = new VolunteerFactory();  
  88.     delete p_student;  
  89.     p_student = NULL;  
  90.     p_student = p_factory->CreateLeiFeng();  
  91.     p_student->Sweep();  
  92.     p_student->Wash();  
  93.     p_student->BuyRice();  
  94.     delete p_factory;  
  95.     p_factory = NULL;  
  96.     delete p_student;  
  97.     p_student = NULL;  
  98.     return 0;  
  99. }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值