Skip to content

Commit

Permalink
[IM]: 简单工厂模式
Browse files Browse the repository at this point in the history
  • Loading branch information
guziqiu committed Jun 28, 2022
1 parent aa3995e commit 725c38c
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions 03.code/18.设计模式/06.简单工厂模式.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#include <iostream>
using namespace std;

// 抽象水果
class AbstractFruit {
public:
virtual void showName() = 0;
};

// apple
class apple : public AbstractFruit {
public:
virtual void showName()
{
cout << "apple" << endl;
}
};

// peer
class peer : public AbstractFruit {
public:
virtual void showName()
{
cout << "peer" << endl;
}
};

// banana
class banana : public AbstractFruit {
public:
virtual void showName()
{
cout << "banana" << endl;
}
};

// 工厂
class FruitFactory {
public:
static AbstractFruit* CreateFruit(const string &flag)
{
if ("apple" == flag)
{
return new apple;
}
else if ("banana" == flag)
{
return new banana;
}
else if ("peer" == flag)
{
return new peer;
}
else
{
return NULL;
}
}
};

void test01()
{
// 创建的过程不需要关心,直接拿来用
FruitFactory *factory = new FruitFactory;
AbstractFruit *fruit = factory->CreateFruit("apple");
fruit->showName();
AbstractFruit *banana = factory->CreateFruit("banana");
banana->showName();

delete fruit;
fruit = factory->CreateFruit("peer");
fruit->showName();
delete factory;
}

int main()
{
test01();

return 0;
}

0 comments on commit 725c38c

Please sign in to comment.