1、定义了一个用于创建对象的接口,让子类决定实例化那一个类。工厂方法使一个类的实例化延迟到其子类。
UML图如下:
2、C++代码实现
- #include <iostream>
- using namespace std;
- class LeiFeng
- {
- public:
- virtual void Sweep() {
- cout << "扫地" << endl;
- }
- virtual void Wash() {
- cout << "洗衣" << endl;
- }
- virtual void BuyRice() {
- cout << "买米" << endl;
- }
- };
- class Undergraduate : public LeiFeng
- {
- public:
- void Sweep() {
- cout << "大学生";
- LeiFeng::Sweep();
- }
- void Wash() {
- cout << "大学生";
- LeiFeng::Wash();
- }
- void BuyRice() {
- cout << "大学生";
- LeiFeng::BuyRice();
- }
- };
- class Volunteer : public LeiFeng
- {
- public:
- void Sweep() {
- cout << "志愿者";
- LeiFeng::Sweep();
- }
- void Wash() {
- cout << "志愿者";
- LeiFeng::Wash();
- }
- void BuyRice() {
- cout << "志愿者";
- LeiFeng::BuyRice();
- }
- };
- //工厂抽象类
- class Factory
- {
- public:
- virtual LeiFeng * CreateLeiFeng() = 0;
- };
- //具体的大学生工厂
- class UndergraduateFactory : public Factory
- {
- public:
- LeiFeng * CreateLeiFeng() {
- return new Undergraduate();
- }
- };
- //具体的志愿者工厂
- class VolunteerFactory : public Factory
- {
- public:
- LeiFeng * CreateLeiFeng() {
- return new Volunteer();
- }
- };
- int main()
- {
- Factory * p_factory = new UndergraduateFactory();
- LeiFeng * p_student = p_factory->CreateLeiFeng();
- p_student->Sweep();
- p_student->Wash();
- p_student->BuyRice();
- delete p_factory;
- p_factory = NULL;
- p_factory = new VolunteerFactory();
- delete p_student;
- p_student = NULL;
- p_student = p_factory->CreateLeiFeng();
- p_student->Sweep();
- p_student->Wash();
- p_student->BuyRice();
- delete p_factory;
- p_factory = NULL;
- delete p_student;
- p_student = NULL;
- return 0;
- }