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


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

现实中,每个公司的产品,都封装成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图片(本实例中没实现)而不是文本

公司一类图:


公司二(三)类图


公司四类图


公司五类图



从以上类图可以看出:

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

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

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

posted on 2023-05-10 10:18  闻缺陷则喜何志丹  阅读(2)  评论(0编辑  收藏  举报  来源