工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
工厂模式根据抽象程度的不同分为三种:简单工厂模式(也叫静态工厂模式)、本文所讲述的工厂方法模式、以及抽象工厂模式。
工厂方法模式在项目中使用得非常频繁,以至于很多代码中都包含工厂方法模式。该模式几乎尽人皆知,但不是每个人都能用得好。熟能生巧,熟练掌握该模式,多思考工厂方法如何应用,而且工厂方法模式还可以与其他模式混合使用(例如模版方法模式、单例模式、原型模式等),变化出无穷的优秀设计,这也正是软件设计和开发的乐趣所在。
自己对工厂方法理解还不够,不过网上有一篇文章写得不错,推荐一下:
http://blog.csdn.net/zhengzhb/article/details/7348707
C++代码如下:
// FactoryMethodPattern.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class LeiFeng
{
public:
void Sweep(){ cout<<"扫地"<<endl; }
void Wash() { cout<<"洗衣"<<endl; }
void BuyRice() { cout<<"买米"<<endl; }
};
class Undergraduate: public LeiFeng
{
};
class Volunteer: public LeiFeng
{
};
class IFactoryMethod
{
public:
virtual LeiFeng* CreateLeiFeng()=0;
};
class CreateUndergraduate: public IFactoryMethod
{
public:
LeiFeng* CreateLeiFeng() { return new Undergraduate; }
};
class CreateVolunteer: public IFactoryMethod
{
public:
LeiFeng* CreateLeiFeng() { return new Volunteer; }
};
int _tmain(int argc, _TCHAR* argv[])
{
IFactoryMethod* ifm = new CreateUndergraduate;
LeiFeng* lf = ifm->CreateLeiFeng();
lf->BuyRice();
lf->Sweep();
lf->Wash();
return 0;
}