首页 > 代码库 > 工厂模式

工厂模式

#ifndef _PRODUCT_H_H
#define _PRODUCT_H_H

class Product
{
public:
virtual ~Product() = 0;
protected:
Product();
private:

};

class ConcreteProduct : public Product
{
public:
ConcreteProduct();
~ConcreteProduct();

protected:

private:
};

class ShapeProduct : public Product
{
public:
ShapeProduct();
~ShapeProduct();
protected:
private:
};
#endif//_PRODUCT_H_H

#ifndef _FACTORY_H_H
#define _FACTORY_H_H

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:
};

class ShapeFactory : public Factory
{
public:
~ShapeFactory();
ShapeFactory();

Product *CreateProduct();
};
#endif //_FACTORY_H_H

#include "factory.h"
#include "Product.h"
#include <iostream>

using namespace std;

Factory::Factory()
{
}

Factory::~Factory()
{
}

ConcreteFactory::ConcreteFactory()
{
cout<<"ConcreteFactory..."<<endl;
}

ConcreteFactory::~ConcreteFactory()
{

}

Product *ConcreteFactory::CreateProduct()
{
return new ConcreteProduct();
}

ShapeFactory::~ShapeFactory()
{}

ShapeFactory::ShapeFactory()
{
cout<<"ShapeFactory..."<<endl;
}

#include "product.h"
#include <iostream>

using namespace std;

Product::Product()
{
}

Product::~Product()
{
}

ConcreteProduct::ConcreteProduct()
{
cout<<"ConcreteProduct..."<<endl;
}

ConcreteProduct::~ConcreteProduct()
{
cout<<"~ConcreteProduct..."<<endl;
}

ShapeProduct::ShapeProduct()
{
cout<<"ShapeProduct"<<endl;
}

ShapeProduct::~ShapeProduct()
{
cout<<"~ShapeProduct"<<endl;
}

#include <iostream>
#include "Factory.h"
#include "Product.h"

using namespace std;

int main(int argc, char *argv[])
{
Factory *fac = new ConcreteFactory();

Product *p = fac->CreateProduct();

Factory *fac2 = new ShapeFactory();
Product *pS = fac2->CreateProduct();

return 0;
}

实现方式:

适用场景:

一般用法: