一、Factory模式的作用:
1、定义创建对象的接口,封装了对象的创建
2、使得具体化类的工作延迟到子类中。
完整实例话代码:
代码片段1:product.h
//Product.h
#ifndef _PRODUCT_H_
#define _PRODUCT_H_
class Product
{
public:
virtual ~Product()=0;
protected:
Product();
private:
};
class ConcreteProduct:public Product
{
public:
~ConcreteProduct();
ConcreteProduct();
protected:
private:
};
代码片段2:Product.cpp
//Product.cpp
#include "Product.h"
#include <iostream>
using namespace std;
Product::Product()
{
}
Product::~Product()
{
}
ConcreteProduct::ConcreteProduct()
{
cout <<"ConcreteProduct....."<<endl;
}
ConcreteProduct::~ConcreteProduct()
{
}
代码片段3:Factory.h
//Factory.h
#ifndef _FACTORY_H_
#define _FACTORY_H_
class Product;
class Factory
{
public:
virtual ~Factory()=0;
virtual Product* CreateProduct()=0;
protected:
Factory();
private:
};
class ConcreteFactory:public Factory
{
public:
~ConcreteFactory();
ConcreteFactory();
Produt* CreateProduct();
private:
};
代码片段4:Factory.cpp
//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();
}
代码片段5:main.cpp
//main.cpp
#include "Factory.h"
#include "Product.h"
#include <iostream>
usinf namespace std;
int main(int argc ,char* argv[])
{
Factory* fac=new ConcreteFactory();
Product* p=fac->CreateProduct();
return 0;
}
二、AbstractFactory类
AbstractFactory模式:创建一组相关或者相互依赖的对象。