组合模式(CompositePattern)
本来都是早上准备设计模式,之后开始一天的工作。然而今天上午有很重要的事情。
最近在倒腾caffe,关于人脸识别的东西。
caffe是基于C++开发的机器学习框架,亮点在于卷积神经网络(最近很火啊)。
顺便为自己吆喝一声,有感兴趣的,可以交流。如果身在济南的,可以当面交流。我QQ544890059,邮件tecsai@163.com.
回归正题--->
基本概念:
组合模式概念比较简单,就是创建一个树形结构,将相近的对象(类的对象或派生类的对象)有层次的放到树形结构上。
由上描述可以看出,组合模式可以很形象的表现出对象之间的层次感。
组合模式是一个结构型模式。
什么时候能用到组合模式:
开发需求中,需要体现层次的时候,当然用组合模式了。
还有打包处理一组对象的时候,嗯,打包。
举个栗子:
一个公司有CEO, CTO, CFO, 以及员工组成。当先有个需求,需要把公司内部的员工信息整理出来,而且要有层次的整理。
上代码:
//H
#pragma once
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class compo
{
public:
compo(string name, string gender,int age);
~compo(void);
public:
void add(compo* ob);
void printob();
vector<compo*> getList();
int getListSize();
private:
string _name;
string _gender;
int _age;
vector<compo*> oblist;//将类作为vector的元素,最好将模板类型设为类的指针
};
//CPP
#include "compo.h"
compo::compo(string name, string gender, int age)
{
_name = name;
_gender = gender;
_age = age;
}
compo::~compo(void)
{
}
void compo::add(compo* ob)
{
oblist.push_back(ob);
}
void compo::printob()
{
cout<<"newobject: "<<endl;
cout<<"ob:"<<_name<<" gender: "<<_gender<<"age: "<<_age<<endl;
}
vector<compo*> compo::getList()
{
return oblist;
}
int compo::getListSize()
{
cout<<oblist.size()<<endl;
return 0;
}
//测试
#include <iostream>
#include "compo.h"
int main()
{
cout<<"compositepattern: "<<endl;
compo* ceo = new compo("Derek","male", 28);
compo* cto = new compo("Derek","male", 28);
compo* cfo = new compo("Anne","female", 28);
compo* employee1 = new compo("Bryan","male", 30);
compo* employee2 = new compo("Sara","male", 31);
compo* employee3 = new compo("Lily","female", 23);
compo* employee4 = new compo("Aigo","male", 50);
ceo->add(cto);
ceo->add(cfo);
cout<<"ceo.size"<<endl;
ceo->getListSize();
cto->add(employee1);
cto->add(employee2);
cout<<"cto.size"<<endl;
cto->getListSize();
cfo->add(employee3);
cfo->add(employee4);
cout<<"cfo.size"<<endl;
cfo->getListSize();
vector<compo*> tList1;
vector<compo*> tList =ceo->getList();
cout<<"size1:"<<tList.size()<<endl;
for(auto i=tList.begin(); i!=tList.end();i++){
(*i)->printob(); //注意(*i)
tList1 = (*i)->getList();
cout<<"size2:"<<tList1.size()<<endl;
for(auto j=tList1.begin();j!=tList1.end(); j++){
(*j)->printob();
}
}
}