写好的代码就是为了以后少写一些代码。
一直找不到合适的例子来演示组合模式,组合模式就像文件夹和文件,像树形的节点和树叶。还是以最经典的例子来演示一下。图元有点、线、圆、方块等,他们组合在一起叫复杂图元。复杂图元组合在一起是另一个复杂图元。
#pragma once
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class 图元
{
public:
virtual string GetName() = 0;
virtual void Render(int depth) = 0;
图元();
virtual ~图元();
};
class 点 : public 图元
{
private:
string name;
public:
点(string name)
{
this->name = name;
}
string GetName()
{
return name;
}
void Render(int depth)
{
for (int i = 0; i < depth; i++)
{
cout << '-';
}
cout << name << endl;
}
};
class 线 : public 图元
{
private:
string name;
public:
线(string name)
{
this->name = name;
}
string GetName()
{
return name;
}
void Render(int depth)
{
for (int i = 0; i < depth; i++)
{
cout << '-';
}
cout << name << endl;
}
};
class 圆 : public 图元
{
private:
string name;
public:
圆(string name)
{
this->name = name;
}
string GetName()
{
return name;
}
void Render(int depth)
{
for (int i = 0; i < depth; i++)
{
cout << '-';
}
cout << name << endl;
}
};
class 长方形 : public 图元
{
private:
string name;
public:
长方形(string name)
{
this->name = name;
}
string GetName()
{
return name;
}
void Render(int depth)
{
for (int i = 0; i < depth; i++)
{
cout << '-';
}
cout << name << endl;
}
};
class 复杂图形 : public 图元
{
private:
string name;
vector<图元 *> vecShape;
public:
复杂图形(string name)
{
this->name = name;
}
~复杂图形()
{
vecShape.clear();
}
string GetName()
{
return name;
}
void Render(int depth)
{
for (int i = 0; i < depth; i++)
{
cout << '-';
}
cout << name << endl;
for (vector<图元*>::iterator it = vecShape.begin(); it != vecShape.end(); it++)
{
(*it)->Render(depth + 4);
}
}
void AddShape(图元 *pShape)
{
vecShape.push_back(pShape);
}
void RemoveShape(图元 *pShape)
{
for (vector<图元*>::iterator it = vecShape.begin(); it != vecShape.end(); it++)
{
if ((*it) == pShape)
{
vecShape.erase(it);
}
}
}
};
// composite.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Shape.h"
int _tmain(int argc, _TCHAR* argv[])
{
复杂图形 *pShape1 = new 复杂图形("复杂图形一");
点 *pPoint1 = new 点("点一");
点 *pPoint2 = new 点("点二");
线 *pLine1 = new 线("线一");
pShape1->AddShape(pPoint1);
pShape1->AddShape(pPoint2);
pShape1->AddShape(pLine1);
复杂图形 *pShape2 = new 复杂图形("复杂图形二");
长方形 *pRectangle = new 长方形("长方形一");
圆 *pCircle = new 圆("圆形一");
pShape2->AddShape(pRectangle);
pShape2->AddShape(pShape1);
pShape2->AddShape(pCircle);
pShape2->Render(4);
delete pShape2;
delete pRectangle;
delete pCircle;
delete pShape1;
delete pPoint1;
delete pPoint2;
delete pLine1;
getchar();
return 0;
}