简单的一个例子是,以生产鞋子为例,厂商有莆田厂,阿迪厂,耐克厂。因此咱们只要告诉别人,咱们的鞋子厂商,就能够知道他们生产出来的鞋子是怎么样的。c++
就是只要只要场地 具体要造啥封装起来。ui
头文件:spa
#include "stdafx.h"
//产品基类
class Shoes {
public:
virtual void shoestype() = 0; //返回鞋子类型
};
//Nike
class NikeShoes:public Shoes
{
public:
void shoestype();
};
//Adi
class AdiShoes:public Shoes
{
public:
void shoestype();
};
//putian
class PutianShoes:public Shoes
{
public:
void shoestype();
};
//工厂基类
class Factory {
public:
virtual Shoes* produceShoes() = 0; //生产鞋子
};
//Nike
class NikeFactory:public Factory
{
public:
Shoes* produceShoes();
};
//Adi
class AdiFactory:public Factory
{
public:
Shoes* produceShoes();
};
//Putian
class PutianFactory:public Factory
{
public:
Shoes* produceShoes();
};
复制代码
实现:code
// FactoryMethod.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "FactoryMethod.h"
using namespace std;
//实现
void NikeShoes::shoestype()
{
cout << "这边是只生产Nike鞋子" << endl;
return;
}
void AdiShoes::shoestype()
{
cout << "这边是只生产阿迪鞋子" << endl;
return;
}
void PutianShoes::shoestype()
{
cout << "这边是只生产莆田鞋子" << endl;
return;
}
Shoes * NikeFactory::produceShoes()
{
return new NikeShoes();
}
Shoes * AdiFactory::produceShoes()
{
return new NikeShoes();
}
Shoes * PutianFactory::produceShoes()
{
return new NikeShoes();
}
int _tmain(int argc, _TCHAR* argv[])
{
Factory * cur_factory = new NikeFactory();
Shoes * cur_shoes = cur_factory->produceShoes();
cur_shoes->shoestype();
int mm ;
cin>> mm;
return 0;
}
复制代码
运行结果:cdn
我我的认为,工厂方法模式,最主要的做用 就是封装了实现的过程。让子类去决定 实例化哪一个类,必须具备建立者和生产者两个类。没有的话用工厂方法模式就不适用了。对象