DesignPattern/01.SimpleFactory/2.Code/SimpleFactory.h

106 lines
1.7 KiB
C
Raw Permalink Normal View History

2019-10-17 13:55:01 +00:00
#ifndef __SIMPLE_FACTORY__
#define __SIMPLE_FACTORY__
#include <iostream>
#include <string.h>
using namespace std;
2021-08-30 13:56:10 +00:00
//抽象产品类AbstractProduct
2019-10-17 13:55:01 +00:00
class AbstractSportProduct
{
public:
AbstractSportProduct(){
}
2021-08-30 13:56:10 +00:00
virtual ~AbstractSportProduct(){};
//抽象方法:
// virtual void printName(){};
virtual void printName() = 0;
// virtual void play(){};
virtual void play() = 0;
2019-10-17 13:55:01 +00:00
};
2021-08-30 13:56:10 +00:00
//具体产品类Basketball
2019-10-17 13:55:01 +00:00
class Basketball :public AbstractSportProduct
{
public:
Basketball(){
printName();
play();
}
~Basketball()
{
2019-10-17 13:55:01 +00:00
}
2021-08-30 13:56:10 +00:00
//具体实现方法
2019-10-17 13:55:01 +00:00
void printName(){
printf("Jungle get Basketball\n");
}
void play(){
printf("Jungle play Basketball\n");
}
};
2021-08-30 13:56:10 +00:00
//具体产品类Football
2019-10-17 13:55:01 +00:00
class Football :public AbstractSportProduct
{
public:
Football(){
printName();
play();
}
~Football()
{
2019-10-17 13:55:01 +00:00
}
2021-08-30 13:56:10 +00:00
//具体实现方法
2019-10-17 13:55:01 +00:00
void printName(){
printf("Jungle get Football\n");
}
void play(){
printf("Jungle play Football\n");
}
};
2021-08-30 13:56:10 +00:00
//具体产品类Volleyball
2019-10-17 13:55:01 +00:00
class Volleyball :public AbstractSportProduct
{
public:
Volleyball(){
printName();
play();
}
~Volleyball()
{
2019-10-17 13:55:01 +00:00
}
2021-08-30 13:56:10 +00:00
//具体实现方法
2019-10-17 13:55:01 +00:00
void printName(){
printf("Jungle get Volleyball\n");
}
void play(){
printf("Jungle play Volleyball\n");
}
};
class Factory
{
public:
std::shared_ptr<AbstractSportProduct> getSportProduct(string productName)
2019-10-17 13:55:01 +00:00
{
std::shared_ptr<AbstractSportProduct> pro;
2019-10-17 13:55:01 +00:00
if (productName == "Basketball"){
pro = std::shared_ptr<AbstractSportProduct>(new Basketball());
2019-10-17 13:55:01 +00:00
}
else if (productName == "Football"){
pro = std::shared_ptr<AbstractSportProduct>(new Football());
2019-10-17 13:55:01 +00:00
}
else if (productName == "Volleyball"){
pro = std::shared_ptr<AbstractSportProduct>(new Volleyball());
2019-10-17 13:55:01 +00:00
}
return pro;
}
};
#endif //__SIMPLE_FACTORY__