表示“部分-整体”关系,并使用户以一致的方式使用单个对象和组合对象。
优点:对于Composite模式,也许人们一开始的注意力会集中在它是如何实现组合对象的。但Composite最重要之处在于用户并不关心是组合对象还是单个对象,用户将以统一的方式进行处理,所以基类应是从单个对象和组合对象中提出的公共接口。
缺点:Composite最大的问题在于不容易限制组合中的组件。
实例代码:
父类
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);
};
MyDecorator类
class MyDecorator:public Graphic
{
public:
MyDecorator(){};
MyDecorator(Graphic* component);
~MyDecorator(){};
virtual void Draw(CDC* pDC);
private:
Graphic* _component;
};
Composite类:
class MyComposite:public Graphic
{
DECLARE_SERIAL(MyComposite)
public:
MyComposite();
~MyComposite(){};
virtual void Draw(CDC * pDC);
virtual void Add(Graphic*);
virtual void Remove();
virtual void Move(POINT Deltapt);
virtual void Serialize(CArchive&);
};
函数实现:
MyComposite::MyComposite()
{
this->iFigureType=FIG_COM;
this->COM=false;
}
void MyComposite::Draw(CDC * pDC)
{
list<Graphic*>::iterator it;
for(it = this->m_lstGraphics.begin(); it != this->m_lstGraphics.end(); ++it)
{
(*it)->Draw(pDC);
}
}
void MyComposite::Add(Graphic* component)
{
m_lstGraphics.push_back(component);
component->COM=TRUE;
list<Graphic*>::iterator it;
int x1=0,y1=0,x2=65530,y2=65530;
for(it = this->m_lstGraphics.begin(); it != this->m_lstGraphics.end(); ++it)
{
x1=max((*it)->ptS.x,x1);
x1=max((*it)->ptE.x,x1);
x2=min((*it)->ptS.x,x2);
x2=min((*it)->ptE.x,x2);
y1=max((*it)->ptS.y,y1);
y1=max((*it)->ptE.y,y1);
y2=min((*it)->ptS.y,y2);
y2=min((*it)->ptE.y,y2);
}
this->ptS.x=x1;
this->ptS.y=y1;
this->ptE.x=x2;
this->ptE.y=y2;
}
void MyComposite::Remove( )
{
this->COM=FALSE;
list<Graphic*>::iterator it;
for(it = this->m_lstGraphics.begin(); it != this->m_lstGraphics.end(); ++it)
{
(*it)->COM=com_remove;
}
}
void MyComposite::Move(POINT Deltapt)
{
list<Graphic*>::iterator it;
int x,y;
x=Deltapt.x;
y=Deltapt.y;
this->ptE.x=ptE.x+x;
this->ptS.x=ptS.x+x;
this->ptE.y=ptE.y+y;
this->ptS.y=ptS.y+y;
for(it = this->m_lstGraphics.begin(); it != this->m_lstGraphics.end(); ++it)
{
(*it)->Move(Deltapt);
}
}
文章评论(0条评论)
登录后参与讨论