设计模式之抽象工厂

软件架构师需要评审概要设计并检查概要设计是否落实,所以设计模式是重点内容之一。


由于是演示程序,不考虑内存泄露

现实中,每个公司的产品,都封装成dll或exe中,其他公司是无法查看和修改的。

公司一定义了类库的标准,公司二和公司三,分别实现了此类库。公司四建立一个产品,公司五在公司四的产品上二次开发。

公司四2014年使用公司二的类库,公司四2015年使用公司三的类库,这对公司五没有任何影响。

使用VC6建立一个基于对话框的程序test1,增加两个按钮,并关联响应函数,主要代码如下:

//第一个公司的产品,定义了接口
//IUnit
class IUnit 
{
public:
	virtual void Draw(CDC& dc)=0;	
};

//IText 文本接口类
class IText : public IUnit
{
public:
	virtual void SetText(const char* pText)=0;
};

//文本类的简单实现
class CText : public IText
{
public :
	virtual void SetText(const char* pText);
protected:
	CString m_strText;
};

void CText::SetText(const char* pText)
{
	m_strText = pText ;
}

//工厂接口类
class IFactory
{
public:
	virtual IText* CreateText()=0;//创建文件类
	//创建图片等类省略
};

//第二个公司的实现
class CText1 : public CText
{
public:
	virtual void Draw(CDC& dc);
};
void CText1::Draw(CDC& dc)
{
	dc.FillRect(CRect(30,30,100,100),&CBrush(RGB(0,255,255)));
	dc.SetTextColor(RGB(255,0,0));
	dc.TextOut(30,30,m_strText);
}

class CFactory1 : public IFactory
{
public :
	virtual IText* CreateText();
};

IText* CFactory1::CreateText()
{
	return new CText1();
}

//第三个公司的实现
class CText2 : public CText
{
public:
	virtual void Draw(CDC& dc);
};
void CText2::Draw(CDC& dc)
{
	dc.FillRect(CRect(30,30,100,100),&CBrush(RGB(255,0,255)));
	dc.SetTextColor(RGB(0,255,0));
	dc.TextOut(30,30,m_strText);
}

class CFactory2 : public IFactory
{
public :
	virtual IText* CreateText();
};
IText* CFactory2::CreateText()
{
	return new CText2();
}

//第四个公司(主程序的实现方)
extern IUnit* Init(IFactory& factory);
void CTest1Dlg::OnButton1() 
{
	//第四个公司的2015年的现实
	IUnit* p = Init(CFactory1());
	CWindowDC dc(this);
	p->Draw(dc);
}

void CTest1Dlg::OnButton2() 
{
	//第四个公司的2016年的现实
	IUnit* p = Init(CFactory2());
	CWindowDC dc(this);
	p->Draw(dc);
}

//第五个公司的实现
IUnit* Init(IFactory& factory)
{	
	IText* p = factory.CreateText();
	p->SetText("尚贤");
	return p;
}

//第六个公司返回的可能是logo图片(本实例中没实现)而不是文本

公司一类图:


公司二(三)类图


公司四类图


公司五类图



从以上类图可以看出:

公司二(公司三)只需要关心公司一

公司四只需要关心公司一和公司二(三)

公司五只需要要关系公司一

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

闻缺陷则喜何志丹

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

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

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

打赏作者

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

抵扣说明:

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

余额充值