#pragma once
class CPeople
{
public:
    CPeople();
    virtual ~CPeople();

public:
     virtual void ReadBook();
};


#include "pch.h"
#include "CPeople.h"

CPeople::CPeople()
{
}


CPeople::~CPeople()
{
}

void CPeople::ReadBook()
{
    cout << "people readbook" << endl;
}
#pragma once
#include "CPeople.h"
class CTeacher :
    public CPeople
{
public:
    CTeacher();
    ~CTeacher();

    virtual void ReadBook();
};

#include "pch.h"
#include "CTeacher.h"


CTeacher::CTeacher()
{
}


CTeacher::~CTeacher()
{
}

void CTeacher::ReadBook()
{
    cout << "teacher book" << endl;
}
#pragma once

class CPeople;

class CSimapleFactoy
{
public:
    static CSimapleFactoy* CreateInstance();

public:

    CPeople* FindValue(int index);

private:
    CSimapleFactoy();
    virtual ~CSimapleFactoy();

private:
    map<int, CPeople*> mapPeople;

    static CSimapleFactoy* _instance;
};

#include "pch.h"
#include "CSimapleFactoy.h"
#include "CPeople.h"
#include "CStudent.h"
#include "CTeacher.h"

//1、工厂创建函数根据当前的类型来实例化对象,返回父类指针
//2、工厂构造时,将所有对象实例化,map<type,*p>形式保存


CSimapleFactoy * CSimapleFactoy::_instance = NULL;

CSimapleFactoy::CSimapleFactoy()
{
    mapPeople.insert(pair<int, CPeople*>(1, new CStudent));
    mapPeople.insert(pair<int, CPeople*>(2, new CTeacher));
}


CSimapleFactoy::~CSimapleFactoy()
{
    map<int, CPeople*>::iterator it = mapPeople.begin();
    for (; it != mapPeople.end(); ++it)
    {
        delete it->second;
        it->second = NULL;
    }
}

CSimapleFactoy * CSimapleFactoy::CreateInstance()
{
    if (NULL == _instance)
    {
        _instance = new CSimapleFactoy;
    }
    return _instance;
}

CPeople * CSimapleFactoy::FindValue(int index)
{
    auto it = mapPeople.find(index);
    if (it != mapPeople.end())
    {
        return it->second;
    }
    return NULL;
}

调用:

    CSimapleFactoy * p = CSimapleFactoy::CreateInstance();
    CPeople* people = p->FindValue(2);
    people->ReadBook();