工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类;工厂方法将一个类的实例化延迟到其子类;
工厂模式实现时,由客户端决定实例化哪一个具体类来实现运算类;即工厂方法把简单工厂的内部判断逻辑延迟到客户端代码来运行;
与简单工厂模式对比:工厂模式克服了简单工厂模式违背了开放-封闭原则的缺点,又保持了封装对象创建过程的优点;
工厂模式UML类图:
工厂模式示例:学雷锋
产品抽象类及具体子类、工厂抽象类及其具体子类的接口:
#ifndef FACTORY_H
#define FACTORY_H
#include <iostream>
#include <string>
using namespace std;
//产品抽象类及具体子类
class LeiFeng
{
public:
virtual void swap(){cout << "swap ";}
virtual void wash(){cout << "wash ";}
virtual void buyrice(){cout << "buyrice ";}
};
class Undergraduate:public LeiFeng
{
void swap(){cout << "Undergraduate swap" << endl;}
void wash(){cout << "Undergraduate wash"<< endl;}
void buyrice(){cout << "Undergraduate buyrice"<< endl;}
};
class Voluteer:public LeiFeng
{
void swap(){cout << "Voluteer swap"<< endl;}
void wash(){cout << "Voluteer wash"<< endl;}
void buyrice(){cout << "Voluteer buyrice"<< endl;}
};
//抽象工厂及具体工厂子类
class IFactory
{
public:
virtual LeiFeng *createLeiFeng()=0;
};
class UndergraduateFactory:public IFactory
{
public:
LeiFeng *createLeiFeng()
{
cout << "UndergraduateFactory:" << endl;
return new Undergraduate();
}
};
class VoluteerFactory:public IFactory
{
public:
LeiFeng *createLeiFeng()
{
cout << "VoluteerFactory:" << endl;
return new Voluteer();
}
};
#endif
客户端代码:
#include "factory.h"
int main()
{
//大学生雷锋工厂
IFactory *factory1 = new UndergraduateFactory();
LeiFeng *std = factory1->createLeiFeng();
std->swap();
std->wash();
std->buyrice();
cout << endl;
//志愿者雷锋工厂
IFactory *factory2 = new VoluteerFactory();
LeiFeng *vol = factory2->createLeiFeng();
vol->swap();
vol->wash();
vol->buyrice();
return 0;
}
代码输出为: