C++设计模式学习笔记五:工厂方法模式

工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。

工厂模式根据抽象程度的不同分为三种:简单工厂模式(也叫静态工厂模式)、本文所讲述的工厂方法模式、以及抽象工厂模式。

工厂方法模式在项目中使用得非常频繁,以至于很多代码中都包含工厂方法模式。该模式几乎尽人皆知,但不是每个人都能用得好。熟能生巧,熟练掌握该模式,多思考工厂方法如何应用,而且工厂方法模式还可以与其他模式混合使用(例如模版方法模式、单例模式、原型模式等),变化出无穷的优秀设计,这也正是软件设计和开发的乐趣所在。

自己对工厂方法理解还不够,不过网上有一篇文章写得不错,推荐一下:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值