Abstract Factory模式

// AbstractFactory.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

//主板
class CMainBoard
{
public:
	//显示主板信息
	virtual void Print() = 0;
};

//华硕主板
class CAsusBoard :public CMainBoard
{
public:
	void Print() {
		printf("Asus MainBoard.\r\n");
	}
};

//技嘉主板
class CGigaByteBoard :public CMainBoard
{
public:

	void Print()
	{
		printf("GigaByte MainBoard.\r\n");
	}
};

class CCPU
{
public:

	//显示CPU信息
	virtual void Print() = 0;
};

//AMD
class CAMDCPU : public CCPU
{
public:

	virtual void Print()
	{
		printf("AMD CPU.\r\n");
	}
};

//Intel
class CIntelCPU : public CCPU
{
public:

	void Print()
	{
		printf("Intel CPU.\r\n");
	}
};

class CComputer
{
protected:
	//主板
	CMainBoard * m_pMainBoard;
	//CPU
	CCPU * m_pCPU;
public:
	//打印电脑配置
	virtual void Print() = 0;
};

//联想电脑
class CLenovoComputer : public CComputer
{
public:
	CLenovoComputer()
	{
		m_pMainBoard = new CGigaByteBoard();
		m_pCPU = new CAMDCPU();
	}

	~CLenovoComputer()
	{
		if (m_pMainBoard)
		{
			delete m_pMainBoard;
			m_pMainBoard = NULL;
		}

		if (m_pCPU)
		{
			delete m_pCPU;
			m_pCPU = NULL;
		}
	}

	void Print()
	{
		m_pMainBoard->Print();
		m_pCPU->Print();
		printf("联想显示器.\r\n");
		printf("8G内存.\r\n");
		printf("512G固态硬盘.\r\n");
	}
};

//Dell电脑
class CDellComputer : public CComputer
{
public:
	CDellComputer()
	{
		m_pMainBoard = new CAsusBoard();
		m_pCPU = new CIntelCPU();
	}

	~CDellComputer()
	{
		if (m_pMainBoard)
		{
			delete m_pMainBoard;
			m_pMainBoard = NULL;
		}

		if (m_pCPU)
		{
			delete m_pCPU;
			m_pCPU = NULL;
		}
	}

	void Print()
	{
		m_pMainBoard->Print();
		m_pCPU->Print();
		printf("戴尔显示器.\r\n");
		printf("8G内存.\r\n");
		printf("1T机械硬盘.\r\n");
	}
};

class CFactory
{
public:
	//得到电脑
	virtual CComputer * GetComputer() = 0;
};

class CLenovoFactory :public CFactory
{
public:
	CComputer * GetComputer()
	{
		return new CLenovoComputer();
	}
};

class CDellFactory : public CFactory
{
public:
	CComputer * GetComputer()
	{
		return new CDellComputer();
	}
};


int main()
{
	CLenovoFactory lf;
	CDellFactory df;

	CComputer * pPC = NULL;

	int nType = 0;

	printf("请输入电脑品牌:\r\n");
	printf("1:联想电脑\r\n");
	printf("2:戴尔电脑\r\n");
	scanf_s("%d", &nType);
	switch (nType)
	{
	case 1:
	{
		pPC = lf.GetComputer();
		if (pPC)
		{
			pPC->Print();
		}
		break;
	}
	case 2:
	{
		pPC = df.GetComputer();
		if (pPC)
		{
			pPC->Print();
		}
		break;
	}
	default:
		printf("输入错误!\r\n");
		break;
	}

	if (pPC)
	{
		delete pPC;
		pPC = NULL;
	}

	return 0;
}



有两个工厂,一个联想工厂,一个戴尔工厂,联想工厂生产联想电脑,戴尔工厂生产戴尔电脑,这个就是 抽象工厂模式。

运行效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孟建行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值