.h
#pragma once
#include <iostream>
using namespace std;
class AbstrctProduct
{
public:
virtual void makePhone() = 0;
};
class xiaoMi:public AbstrctProduct
{
public:
virtual void makePhone() override;
};
class huaWei :public AbstrctProduct
{
public:
virtual void makePhone() override;
};
class Factory
{
public:
Factory();
AbstrctProduct* get_product(int num); //获取产品指针
public:
AbstrctProduct* curProduct;
};
.cpp
#include "SampleFactory.h"
int main()
{
Factory* F = new Factory;
AbstrctProduct* A = F->get_product(1);
A->makePhone();
AbstrctProduct* B = F->get_product(2);
B->makePhone();
delete A;
A = nullptr;
delete B;
B = nullptr;
delete F;
F = nullptr;
return 0;
}
void xiaoMi::makePhone()
{
cout << "小米手机" << endl;
}
void huaWei::makePhone()
{
cout << "华为手机" << endl;
}
Factory::Factory()
{
this->curProduct = nullptr;
}
AbstrctProduct* Factory::get_product(int num)
{
switch (num)
{
case 1:
this->curProduct = new xiaoMi;
case 2:
this->curProduct = new huaWei;
default:
break;
}
return this->curProduct;
}
结果: