|
@@ -0,0 +1,121 @@
|
|
|
+#include<array>
|
|
|
+#include<iostream>
|
|
|
+#include<vector>
|
|
|
+//组合模式
|
|
|
+//组合模式的核心在于能够直观的展示出数据的组合形式,同时隐藏组成形式不同带来的影响
|
|
|
+//即为不同的组合形式对外提供了相同的接口,迭代器是一种很好的隐藏组合模式的方法
|
|
|
+
|
|
|
+//一个不带组合模式的示例
|
|
|
+class person //一个游戏角色
|
|
|
+{
|
|
|
+private:
|
|
|
+ int defense; //防御
|
|
|
+ int blood; //血量
|
|
|
+public:
|
|
|
+ person(int _defense,int _blood):defense(_defense),blood(_blood)
|
|
|
+ {}
|
|
|
+ int code(int x) //计算人物的战力
|
|
|
+ {
|
|
|
+ auto i=static_cast<int>(defense+blood);
|
|
|
+ return i;
|
|
|
+ }
|
|
|
+
|
|
|
+};
|
|
|
+//但是上面有个问题,如果我们还要加上免伤呢,或者还要其他东西叠加上去怎么办?
|
|
|
+//最简单的办法当然是直接修改这个类,但是然后呢,所有的函数都要修改进行适配似乎不太现实
|
|
|
+
|
|
|
+//数组组合模式可以很好的解决这个问题
|
|
|
+//直接用数组提供的迭代器就能很好的解决这个问题
|
|
|
+
|
|
|
+enum character
|
|
|
+{
|
|
|
+ defense,
|
|
|
+ blood,
|
|
|
+ attact
|
|
|
+};
|
|
|
+
|
|
|
+class group
|
|
|
+{
|
|
|
+private:
|
|
|
+ std::array<int,attact> human;
|
|
|
+public:
|
|
|
+ int code()
|
|
|
+ {
|
|
|
+ int count=0;
|
|
|
+ for(int i:human)
|
|
|
+ {
|
|
|
+ count+=i;
|
|
|
+ }
|
|
|
+ return count;
|
|
|
+ }
|
|
|
+};
|
|
|
+
|
|
|
+//图形组合
|
|
|
+//将多个类进行拼装拼装成一个类然后将拼装后的类作为一个整体进行操作
|
|
|
+//又涉及到了复杂的继承操作
|
|
|
+
|
|
|
+enum class type
|
|
|
+{
|
|
|
+ photo,
|
|
|
+ cartoon,
|
|
|
+ draws,
|
|
|
+};
|
|
|
+class griph_base
|
|
|
+{
|
|
|
+public:
|
|
|
+ virtual void draw()=0;
|
|
|
+};
|
|
|
+
|
|
|
+class draws:public griph_base
|
|
|
+{
|
|
|
+private:
|
|
|
+ type typide;
|
|
|
+ std::array<int,15> data;
|
|
|
+public:
|
|
|
+ void draw()override
|
|
|
+ {
|
|
|
+ }
|
|
|
+};
|
|
|
+
|
|
|
+
|
|
|
+class photo:public griph_base
|
|
|
+{
|
|
|
+private:
|
|
|
+ type typide;
|
|
|
+ std::array<int,15> data;
|
|
|
+public:
|
|
|
+ void draw()override
|
|
|
+ {
|
|
|
+ }
|
|
|
+};
|
|
|
+
|
|
|
+class cartoon:public griph_base
|
|
|
+{
|
|
|
+private:
|
|
|
+ type typide;
|
|
|
+ std::array<int,15> data;
|
|
|
+public:
|
|
|
+ void draw()override
|
|
|
+ {
|
|
|
+ }
|
|
|
+};
|
|
|
+
|
|
|
+
|
|
|
+class map_combinate
|
|
|
+{
|
|
|
+private:
|
|
|
+ std::vector<griph_base*> data; //基类指针指向子类
|
|
|
+public:
|
|
|
+ void draw()
|
|
|
+ {
|
|
|
+ for(auto i:data)
|
|
|
+ {
|
|
|
+ i->draw();
|
|
|
+ }
|
|
|
+ }
|
|
|
+};
|
|
|
+
|
|
|
+int main()
|
|
|
+{
|
|
|
+
|
|
|
+}
|