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



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

运行效果如下:

Abstract Factory模式_第1张图片

你可能感兴趣的:(设计模式)