设计模式(2)-简单工厂模式

简单工厂模式是什么?

简单工厂是指在基类中对一系列具有相同行为的对象按需创建的方法。
被创建的对象通常具有共同的基类。

类图如下:

https://s3.bmp.ovh/imgs/2021/10/9cec1053d7b18b98.jpeg

简单工厂示例:水果

https://s3.bmp.ovh/imgs/2021/10/e10ec890673cfc23.jpeg

/**
* 简单工厂模式
*/
#include <iostream>
#include <string>
#include <algorithm>

class Fruit {
public:
virtual void grow() = 0;
virtual void plant() = 0;
virtual void harvest() = 0;
};

class Apple : public Fruit {
public:
void grow() override
{
std::cout << "grow apple" << std::endl;
}
void plant() override
{
std::cout << "plant apple" << std::endl;
}
void harvest() override
{
std::cout << "harvest apple" << std::endl;
}
void SetTreeAge(uint32_t treeAge) { treeAge_ = treeAge; }
uint32_t GetTreeAge() const { return treeAge_; }

private:
uint32_t treeAge_ = 0;
};

class Grape : public Fruit {
public:
void grow() override
{
std::cout << "grow grape" << std::endl;
}
void plant() override
{
std::cout << "plant grape" << std::endl;
}
void harvest() override
{
std::cout << "harvest grape" << std::endl;
}
void SetSeedless(bool seedless) { seedless_ = seedless; }
bool IsSeedledd() const { return seedless_; }

private:
bool seedless_ = false;
};

class FruitGardener {
public:
static Fruit *Factory(const std::string &fruit)
{
if (fruit == "apple") {
return new Apple();
} else if (fruit == "grape") {
return new Grape();
} else {
std::cerr << "bad fruit to create" << std::endl;
return nullptr;
}
}
};

int main()
{
std::cout << "=== create apple ===" << std::endl;
auto *apple = FruitGardener::Factory("apple");
apple->grow();
apple->harvest();
apple->plant();

std::cout << "=== create grape ===" << std::endl;
auto *grape = FruitGardener::Factory("grape");
grape->grow();
grape->harvest();
grape->plant();

delete apple;
delete grape;
}

输出:

=== create apple ===
grow apple
harvest apple
plant apple
=== create grape ===
grow grape
harvest grape
plant grape

参考

《Java与模式》第12章