Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1811319
  • 博文数量: 496
  • 博客积分: 12043
  • 博客等级: 上将
  • 技术积分: 4778
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-27 14:26
文章分类

全部博文(496)

文章存档

2014年(8)

2013年(4)

2012年(181)

2011年(303)

2010年(3)

分类: C/C++

2012-06-05 10:17:26

工厂方法有点:
       修正了简单工厂模式中不遵守开放-封闭原则。工厂方法模式把选择判断移到了客户端去实现,如果想添加新功能就不用修改原来的类,直接修改客户端即可。

下面是代码:
#include
#include

using namespace std;

//实例基类,相当于Product(为了方便没有抽象)
class LeiFeng
{
public:
    virtual void Sweep()
    {
    cout << "雷锋扫地" << endl;
    }
};

//学雷锋的大学生,相当于ConcreteProduct
class Student : public LeiFeng
{
public:
    virtual void Sweep()
    {
    cout << "大学生扫地" << endl;
    }
};

//学雷锋的志愿者,相当于ConcreteProduct
class Volenter : public LeiFeng
{
public:
    virtual void Sweep()
    {
    cout << "志愿者扫地" << endl;
    }
};

//工厂基类Creator
class LeiFengFactory
{
public:
    virtual LeiFeng* CreateLeiFeng()
    {
    return new LeiFeng();
    }
};

//工厂具体类
class StudentFactory : public LeiFengFactory
{
public:
    virtual LeiFeng* CreateLeiFeng()
    {
    return new Student();
    }
};

class VolenterFactory: public LeiFengFactory
{
public:
    virtual LeiFeng* CreateLeiFeng()
    {
    return new Volenter();
    }
};

//客户端
int main()
{
    LeiFengFactory* lf = new LeiFengFactory();
    LeiFeng* s = lf->CreateLeiFeng();
    s->Sweep();
    delete s;
    delete lf;
   
    lf = new StudentFactory();
    s = lf->CreateLeiFeng();
    s->Sweep();
    delete s;
    delete lf;
   
    lf = new VolenterFactory();
    s = lf->CreateLeiFeng();
    s->Sweep();
    delete s;
    delete lf;
   
    return 0;
}

阅读(547) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~