factory 模式
功能:
1) 定义创建对象的接口,封装了对象的创建
2) 使得具体化类的工作延迟到了子类中
//product.h
#ifndef _PRODUCT_H
#define _PRODUCT_H
class Product
{
public:
virtual ~ Product() = 0;
protected:
Product();
};
class ConcreteProduct : public Product
{
public:
~ConcreteProduct();
ConcreteProduct();
};
#endif
------------------------------------------
//Product.cpp
#include
#include "Product.h"
using namespace std;
Product::Product()
{
}
Product::~Product()
{
}
ConcreteProduct::ConcreteProduct()
{
cout << "ConcreteProduct..." << endl;
}
ConcreteProduct::~ConcreteProduct()
{
}
------------------------------------
//Factory.h
#ifndef _FACTORY_H
#define _FACTORY_H
class Product;
class Factory
{
public:
virtual ~Factory() = 0;
virtual Product * CreateProduct() = 0;
protected:
Factory();
};
class ConcreteFactory:public Factory
{
public:
~ConcreteFactory();
ConcreteFactory();
Product * CreateProduct();
};
#endif
---------------------------------
//Factory.cpp
#include "Factory.h"
#include "Product.h"
#include
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
using namespace std;
int main(int argc, char * argv[])
{
Factory * fac = new ConcreteFactory();
Product * p = fac->CreateProduct();
return 0;
}
阅读(525) | 评论(0) | 转发(0) |