简单工厂要添加新类时,得在工厂类里面修改,添加判断生成新类的条件,这样破坏了开放-封闭的原则,内部改动,但是好处是,判断选择生成哪种类的对象交给了简单工程,而不是客户端这里
而工厂方法模式改良了简单工厂模式,每种类对象对应了一个生成该类对象的工厂类,当添加新类时,只要写个新类,再写个生成这个新类对象的工厂类,不需改内部代码,满足开放-封闭原则,缺点是生成什么类型的对象就得选用什么类型的工厂,这个选择交给了客户端,没有封装起来
//factory.h
#ifndef _FACTORY_H_
#define _FACTORY_H_
#include <iostream>
#include <string>
using namespace std;
class Leifeng
{
public:
void Wash()
{
cout << "洗衣服" << endl;
}
void Sweep()
{
cout << "扫地" << endl;
}
void BuyRice()
{
cout << "买米" << endl;
}
virtual void call() = 0;
};
class Ungraduate: public Leifeng
{
public:
void call()
{
cout << "我是大学生" << endl;
}
};
class Volunteer: public Leifeng
{
public:
void call()
{
cout << "我是志愿者" << endl;
}
};
class Factory
{
public:
static Leifeng *create(string &type)
{
Leifeng *person = NULL;
if(type.compare("大学生") == 0)
person = new Ungraduate();
else if(type.compare("志愿者") == 0)
person = new Volunteer();
return person;
}
};
class iFactory
{
public:
virtual Leifeng *createLeifeng() = 0;
};
class UngraduateFactory: public iFactory
{
public:
Leifeng *createLeifeng()
{
return new Ungraduate();
}
};
class VolunteerFactory: public iFactory
{
public:
Leifeng *createLeifeng()
{
return new Volunteer();
}
};
#endif
#include <iostream>
#include <cstdio>
#include "factory.h"
using namespace std;
int main()
{
string type1("大学生");
string type2("志愿者");
Leifeng *p = NULL;
p = Factory::create(type1);
if(p != NULL)
{
p->call();
p->Sweep();
p->Wash();
p->BuyRice();
delete p;
p = NULL;
}
cout << endl << endl;
iFactory *f = NULL;
if(type2.compare("大学生") == 0)
f = new UngraduateFactory();
else if(type2.compare("志愿者") == 0)
f = new VolunteerFactory();
if(f != NULL)
{
p = f->createLeifeng();
p->call();
p->Sweep();
p->Wash();
p->BuyRice();
delete p;
p = NULL;
delete f;
f = NULL;
}
return 0;
}