以下是一个具体的例子,很直观
定义一个抽象产品 手机类

class Phone
{
public :
virtual void call()=0;//打电话
virtual void music()=0;//音乐
virtual void internet()=0;//上网
};

实现产品类1:实现一个iphone
class iPhone:public Phone
{
public:
void call()
{
std::cout<<"用iphone打电话"<<std::endl;
}
void music()
{
std::cout<<"用iphone听音乐"<<std::endl;
}
void internet()
{
std::cout<<"用iphone上网"<<std::endl;
}
};

实现产品类2:Android手机
class AndroidPhone:public Phone
{
public:
void call()
{
std::cout<<"用Android手机打电话"<<std::endl;
}
void music()
{
std::cout<<"用Android手机听音乐"<<std::endl;
}
void internet()
{
std::cout<<"用Android手机上网"<<std::endl;
}
};


抽象一个工厂(富士康、华为是代工厂)
class AbstractFactory
{
public:
virtual Phone * createPhone()=0;
};

实现抽象类 富士康工厂,生产iPhone

class Foxconn:public AbstractFactory
{
public:
Phone * createPhone()
{
return new iPhone;
}
};
实现抽象类 华为工厂,生产AndroidPhone

class Huawei:public AbstractFactory
{
public:
Phone * createPhone()
{
return new AndroidPhone;
}
};

以下是此问题的源代码(C++):

Factory.h

#ifndef _FACTORY_H
#define _FACTORY_H
#include<iostream>
class Phone//抽象产品类 手机
{
public :
	virtual void call()=0;//打电话    均定义为纯虚函数,或者定义为虚函数加上实现
	virtual void music()=0;//听音乐
	virtual void internet()=0;//上网
};
class iPhone:public Phone//实现iPhone类
{
public:
	void call()
	{
		std::cout<<"用iphone打电话"<<std::endl;
	}
	void music()
	{
		std::cout<<"用iphone听音乐"<<std::endl;
	}
	void internet()
	{
		std::cout<<"用iphone上网"<<std::endl;
	}
};

class AndroidPhone:public Phone//实现AndroidPhone类
{
public:
	void call()
	{
		std::cout<<"用Android手机打电话"<<std::endl;
	}
	void music()
	{
		std::cout<<"用Android手机听音乐"<<std::endl;
	}
	void internet()
	{
		std::cout<<"用Android手机上网"<<std::endl;
	}
};


class AbstractFactory//抽象工厂类 手机生产代工厂
{
public:
	virtual Phone * createPhone()=0;//Phone类型的指针函数
};
class Foxconn:public AbstractFactory//实现Foxconn类,生产iPhone
{
public:
	Phone * createPhone()
	{
		return new iPhone;
	}
};
class Huawei:public AbstractFactory//实现Huawei类,生产AndroidPhone
{
public:
	Phone * createPhone()
	{
		return new AndroidPhone;
	}
};
#endif

Factory.cpp

#include "Factory.h"

int _tmain(int argc, _TCHAR* argv[])
{
	AbstractFactory *foxconn=new Foxconn();
	Phone * iphone=foxconn->createPhone();
	iphone->call();
	iphone->music();
	iphone->internet();


	AbstractFactory *huawei=new Huawei();
	Phone * androidphone=huawei->createPhone();
	androidphone->call();
	androidphone->music();
	androidphone->internet();

	return 0;
}

运行结果如下:

更多推荐