设计模式
1. 工厂模式
1.1. 示例 - V1版本 :使用new,C++98版本(常规版本)
#include
//当类里面没有数据只有纯虚方法时称之为接口
class Bird // 接口
{
public:
Bird()
{
std::cout << "Bird Construct" << std::endl;
}
//定义为纯虚函数后,在析构时,也会执行子类的析构函数。否则,子类的析构函数不会执行。
//详细原理性说明,详见: 《构造函数、类成员、析构函数调用顺序》
virtual ~Bird()
{
std::cout << "~Bird Destruct" << std::endl;
}
virtual void eat() = 0; //纯虚函数,在子类中必须实现,否则无法编译通过。
virtual void fly() = 0;
};
class Parrot : public Bird
{
public:
Parrot()
{
std::cout << "Parrot Construct" << std::endl;
}
virtual ~Parrot() .
{
std::cout << "~Parrot Destruct" << std::endl;
}
void eat()
{
std::cout << "Parrot::eat" << std::endl;
}
void fly()
{
std::cout << "Parrot::fly" << std::endl;
}
};
class Swallow : public Bird
{
public:
Swallow()
{
std::cout << "Swallow Construct" << std::endl;
}
virtual ~Swallow() .
{
std::cout << "~Swallow Destruct" << std::endl;
}
void eat()
{
std::cout << "Swallow::eat" << std::endl;
}
void fly()
{
std::cout << "Swallow::fly" << std::endl;
}
};
enum EM_BRID_TYPE
{
EM_BRID_TYPE_PARROT = 1,
EM_BRID_TYPE_SWALLOW =2
};
class BirdFactory//工厂
{
public:
BirdFactory() { std::cout << "BirdFactory" << std::endl; }
virtual ~BirdFactory() { std::cout << "~BirdFactory" << std::endl; }
Bird* createBrid(EM_BRID_TYPE birdType)
{
if(birdType == EM_BRID_TYPE_PARROT)
return new Parrot();
else if(birdType == EM_BRID_TYPE_SWALLOW)
return new Swallow();
else
return nullptr;
}
};
int main()
{
BirdFactory* factory = new BirdFactory();
Bird* bird1 = factory->createBrid(EM_BRID_TYPE_PARROT);
bird1->eat();
bird1->fly();
Bird* bird2 = factory->createBrid(EM_BRID_TYPE_SWALLOW);
bird2->eat();
bird2->fly();
delete bird1;
delete bird2;
delete factory;
return 0;
}
运行结果:
1.2. 示例 - V2版本 :使用new + 前置对象创建过程
#include
#include
#include
#include
运行结果:
1.3. 示例 - V3版本 - 使用 std::make_shared,C++11以上版本
#include
#include
#include
#include
运行结果: