1,产品头文件:
#ifndef _PRODUCT_H_
#define _PRODUCT_H_
class Carcase
{
public:
~Carcase(){}
Carcase(){}
protected:
private:
};
class wheel
{
public:
~wheel(){}
wheel(){}
protected:
private:
};
class Tyre
{
public:
~Tyre(){}
Tyre(){}
protected:
private:
};
class Engine
{
public:
~Engine(){}
Engine(){}
protected:
private:
};
class Motor
{
public:
~Motor()
{
this->car = 0;
this->whe = 0;
this->tyr = 0;
this->eng = 0;
}
Motor(){}
void setcar(Carcase* _car)
{
this->car = _car;
}
void setwhe(wheel* _whe){this->whe = _whe;}
void settyr(Tyre* _tyr){this->tyr = _tyr;}
void seteng(Engine* _eng){this->eng = _eng;}
protected:
private:
Carcase* car;
wheel* whe;
Tyre* tyr;
Engine* eng;
};
#endif
2,工厂头文件:
#ifndef _FACTORY_H_
#define _FACTORY_H_
#include "Product.h"
class Factory
{
public:
~Factory(){}
Factory(){}
Carcase* CreateCarcase(){return new Carcase();}
wheel* CreateWheel(){return new wheel();}
Engine* CreateEngine(){return new Engine();}
Tyre* CreateTyre(){return new Tyre();}
protected:
private:
};
#endif
3,装配器头文件:
#ifndef _ASSEMBLER_H_
#define _ASSEMBLER_H_
#include "Factory.h"
class Assembler
{
public:
Assembler(Factory* fac)
{
this->fac = fac;
}
~Assembler(){}
Motor* GenerateMotor()
{
this->mot = new Motor();
mot->setcar(fac->CreateCarcase());
mot->seteng(fac->CreateEngine());
mot->settyr(fac->CreateTyre());
mot->setwhe(fac->CreateWheel());
return mot;
}
protected:
private:
Factory* fac;
Motor* mot;
};
#endif
4,客户端测试:
#include "Assembler.h"#include <iostream>
using namespace std;
int main()
{
Assembler* ass = new Assembler(new Factory());
Motor* mot = ass->GenerateMotor();
getchar();
return 0;
}