最近在看C++设计模式,这里做一点记录,以后复习可能会有不一样的见解。
Factory模式:
两个重要功能:
1、定义创建对象的接口,封装了对象的创建
2、使得具体化类的工作延迟到了子类中
具体实现如下:
//Product.h
#pragma once
//产品基类,用于后期指向ConcreteProduct实例
class Product
{
public:
virtual ~Product() = 0;
//将析构函数声明为纯虚函数,这样会产生抽象类,抽象类是不能实例化的,只能作为基类。但是仍要在cpp文件中实现析构函数,因为析构是从基类到父类逐层进行的,如果到基类没有析构实现的话会报错。
protected:
private:
};
class ConcreteProduct:public Product
{
public:
~ConcreteProduct();
ConcreteProduct();
protected:
private:
}
//Product.cpp
#include "Product.h"
#include <iostream>
using namespace std;
Product::Product()
{
}
Product::~Product()
{
}
ConcreteProduct::ConcreteProduct()
{
count<<"ConcreteProduct..."<<endl;
}
ConcreteProduct::~ConcreteProduct()
{
}
//Factory.h
#pragma once
class Product; //这边用了前向申明,避免了头文件的互相包含
class Factory
{
public:
virtual ~Factory() = 0;
virtual Product* CreateProduct() = 0;
protected:
Factory();
private:
}
class ConcreteFactory:public Factory
{
public:
~ConcreteFactory();
ConcreteFactory();
Product* CreateProduct();
protected:
private:
};
//Factory.cpp
#include "Product.h"
#include "Factory.h"
#include <iostream>
using namespace std;
Factory::Factory()
{
}
Factory::~Factory()
{
}
ConcreteFactory::ConcreteFactory()
{
cout<<"ConcreteFactory..."<<endl;
}
ConcreteFactory::~ConcreteFactory()
{
}
Product* ConcreteFactory::CreateProduct()
{
return new ConcreteProduct();
}
//main.cpp
#include "Factory.h"
#include "Product.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
//用父类指针指向基类实现多态
Factory* fac = new ConcreteFactory();
//因为CreateProduct是虚函数,所以调用的是ConcreteFactory的CreateProduct方法。
Product* p = fac->CreateProduct();
getchar();
return 0;
}