工厂方法 == 开闭原则 + 简单工厂
一.优点
- 实现了对象创建和使⽤的分离。
- 系统的可扩展性也就变得⾮常好,⽆需修改接⼝和原类。
二.缺点
- 增加了类的个数,增加了系统的抽象性和理解难度
三.使用场景
- 调用者不知道它所需要的对象的类。
- 抽象⼯⼚类通过其⼦类工厂来指定创建哪个对象。
//Fruit.h
#pragma once
#include <string>
//抽象水果类
class Fruit
{
public:
virtual std::string GetName() = 0;
};
//苹果类:public Fruit
class Apple :public Fruit
{
public:
std::string GetName() override;
};
//香蕉类:public Fruit
class Banana :public Fruit
{
public:
std::string GetName() override;
};
//抽象工厂类
class AbstractFactory
{
public:
virtual Fruit* CreateFruit() = 0;
};
//苹果工厂类:public AbstractFactory
class AppleFactory :public AbstractFactory
{
public:
Fruit* CreateFruit() override;
};
class BananaFactory :public AbstractFactory
{
public:
Fruit* CreateFruit() override;
};
//Fruit.cpp
#include "Fruit.h"
#include <iostream>
std::string Apple::GetName()
{
std::cout << "here is Apple" << std::endl;
return std::string("Apple");
}
std::string Banana::GetName()
{
std::cout << "here is Banana" << std::endl;
return std::string("Banana");
}
Fruit* AppleFactory::CreateFruit()
{
return new Apple;
}
Fruit* BananaFactory::CreateFruit()
{
return new Banana;
}
//main.cpp
#include "Fruit.h"
#include <iostream>
int main()
{
Fruit* apple = nullptr;
AppleFactory apple_factory;
apple = apple_factory.CreateFruit();
std::cout << apple->GetName() << std::endl;
if (apple!= nullptr)
{
delete apple;
apple = nullptr;
}
Fruit* banana = nullptr;
BananaFactory banana_factory;
banana = banana_factory.CreateFruit();
std::cout << banana->GetName() << std::endl;
if (banana != nullptr)
{
delete banana;
banana = nullptr;
}
system("pause");
return 0;
}