将一个类的接口转换成客户希望的另外一个接口,解决两个已有接口之间不匹配的问题。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
结构图
(1)class adapter
(2)object adapter
推荐使用第二种
示例代码(在矢量画图软件中,使用edit框进行文本书写,其中MyText为适配器)
父类
class Graphic : public CObject
{
DECLARE_SERIAL(Graphic)
public:
virtual void Draw(CDC* pDC);
Graphic(){};
Graphic(Graphic* component);
Graphic(POINT pte1,POINT pts1,int iFigureType1);
POINT ptS;//起点
POINT ptE;//终点
BOOL Tip;
int iFigureType;//画图类型
Graphic* component;
virtual void Serialize(CArchive& ar);
virtual ~Graphic();
};
其中一个子类MyLine
class MyLine:public Graphic
{
DECLARE_SERIAL(MyLine)
int ipenType;//画笔类型
COLORREF PenCor;//画笔颜色
MyLine(){};
MyLine(POINT pte1,POINT pts1,int ipenType1,COLORREF PenCor1);
~MyLine(){};
virtual void Serialize(CArchive&);
virtual void Draw(CDC* pDC);
};
adapter类
class MyText:public Graphic
{
DECLARE_SERIAL(MyText)
COLORREF TextCor;//文本颜色
CString pBuf;
LOGFONT pFont;
CEdit * m_Edit1;
MyText(){};
MyText(POINT pte1,POINT pts1,CString pBuf1,LOGFONT pFont1,COLORREF TextCor1);
~MyText(){};
void CreatEedit(CWnd* pParentWnd);
void GetStr();
virtual void Serialize(CArchive&);
virtual void Draw(CDC* pDC);
};
主要实现:
void MyText::Serialize(CArchive& ar)
{
CString faceName;
CObject::Serialize(ar);
if(ar.IsStoring())
ar <<iFigureType<<ptS<<ptE<<COM<< TextCor<<pBuf<<pFont.lfHeight<<pFont.lfWidth<<pFont.lfEscapement
<<pFont.lfOrientation<<pFont.lfWeight<<pFont.lfItalic
<<pFont.lfUnderline<<pFont.lfStrikeOut<<pFont.lfCharSet
<<pFont.lfOutPrecision<<pFont.lfClipPrecision<<pFont.lfQuality
<<pFont.lfPitchAndFamily<<CString(pFont.lfFaceName);//<<pFont.lfFaceName;
else //loading, not storing
ar >>iFigureType>>ptS>>ptE>>COM>>TextCor>>pBuf>>pFont.lfHeight>>pFont.lfWidth>>pFont.lfEscapement
>>pFont.lfOrientation>>pFont.lfWeight>>pFont.lfItalic
>>pFont.lfUnderline>>pFont.lfStrikeOut>>pFont.lfCharSet
>>pFont.lfOutPrecision>>pFont.lfClipPrecision>>pFont.lfQuality
>>pFont.lfPitchAndFamily>>faceName;
lstrcpy(pFont.lfFaceName, faceName.GetBuffer(faceName.GetLength()));//>>pFont.lfFaceName;
}
void MyText::CreatEedit(CWnd* pParentWnd)
{
this->m_Edit1=new CEdit();
m_Edit1->Create(WS_CHILD|WS_VISIBLE|WS_BORDER|ES_AUTOHSCROLL|ES_MULTILINE,CRect(ptS.x,ptS.y,ptE.x,ptE.y), pParentWnd,NULL);
this->m_Edit1->SetFocus( );
}
void MyText::Draw(CDC * pDC)
{
CFont* cFont;
cFont=new CFont();
cFont->CreateFontIndirect(&pFont);
CFont* poldFont=pDC->SelectObject(cFont);
pDC->SetTextColor(TextCor);
CRect rect=CRect(ptS.x, ptS.y, ptE.x, ptE.y);
pDC->DrawText(pBuf,&rect,DT_LEFT);
DeleteObject(poldFont);
DeleteObject(cFont);
}
文章评论(0条评论)
登录后参与讨论