设计模式16——工厂模式

抽象工厂中,不同的对象通过的不同的输入符号来判断。当要添加新的类时,需要修改工厂类,不利于扩展。

工厂模式中,不同的类由不同的工厂创建出来,相互之间不受影响。

#ifndef Factory_H_H
#define Factory_H_H

#include <iostream>
#include <string>
using namespace std;

class Person{
protected:
    string strName;
public:
    Person(){
    }

    void show(){
        cout << "This is " << strName << endl;
    }
};

class Student : public Person{
public:
    Student(){
        strName = "Student";
    }
};

class Teacher : public Person{
public:
    Teacher(){
        strName = "Teacher";
    }
};

class Factory{
public:
    virtual Person *create() = 0;
};

class StudentFactory : public Factory{
public:
    Person *create(){
        return new Student();
    }
};

class TeacherFactory : public Factory{
public:
    Person *create(){
        return new Teacher();
    }
};


void FactoryTest(){
    Factory *factory1 = new StudentFactory();
    factory1->create()->show();

    Factory *factory2 = new TeacherFactory();
    factory2->create()->show();

}

#endif
原文地址:https://www.cnblogs.com/MiniHouse/p/4589688.html