Composite(组合)模式

模式结构图
背景:
在软件某些情况下,客户代码过多的依赖于对象容器复杂的内部实现结构,对象容器内部实现结构(而非抽象接口)的变化将引起客户代码的频繁变化,带来了代码的维护性、扩展性等弊端。
特点:
1.将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一种一致性(稳定)。
2.Composite模式采用树形结构来实现普遍存在的对象容器,从而将一对多的关系转化一对一的关系,使得客户代码可以一致的(复用)处理对象和容器对象,无需关心处理的是单个对象还是组合对象容器。
3.将客户代码与负责的对象容器结构解耦是Composite的核心思想,解耦合之后,客户代码将与纯粹的抽象接口-而非对象容器的内部实现结构-发生依赖,从而更能应对变化。
4.Composite模式在具体的实现中,可以让父对象的子对象反向追溯。如果父对象又频繁的遍历需求,可使用缓存技巧来改善效率。
Component.h

#pragma once
class Component {
public:
	virtual ~Component();
	Component();
	virtual void addComponent(Component* comp);
	virtual void removeComponent(Component* comp);
	virtual Component* getindex(int index);
	virtual void Operation() = 0;
};

Component.cpp

#include"Component.h"
Component::Component() {

}
Component::~Component() {

}
void Component::addComponent(Component* comp) {

}
void Component::removeComponent(Component* comp) {

}
Component* Component::getindex(int index) {
	return nullptr;
}

Composite.h

#pragma once
#include"Component.h"
#include<list>
using namespace std;
class Composite {
public:
	Composite();
	~Composite();
	void addComponent(Component* comp);
	void removeComponent(Component* comp);
	Component* getindex(int index);
	void Operation();
protected:
	list<Component*> comlist;
};

Composite.cpp

#include"Composite.h"
#include"Component.h"
Composite::Composite() {

}
Composite::~Composite() {

}
void Composite::addComponent(Component* comp) {
	comlist.push_back(comp);
}
void Composite::removeComponent(Component* comp) {
	comlist.remove(comp);
}
Component* Composite::getindex(int index) {
	list<Component*>::iterator it = comlist.begin();
	int count = 0;
	for (; it != comlist.end(); it++) {
		if (count == index) {
			break;
		}
		count++;
	}
	return *it;
}
void Composite::Operation() {
	list<Component*>::iterator it = comlist.begin();
	for (; it != comlist.end(); it++) {
		(*it)->Operation();
	}
}

Leaf.h

#pragma once
#include"Component.h"
class Leaf :public Component {
public:
	Leaf();
	~Leaf();
	void Operation();
};

Leaf.cpp

#include"Leaf.h"
#include<iostream>
using namespace std;
Leaf::Leaf() {

}
Leaf::~Leaf() {

}
void Leaf::Operation() {
	cout << "leaf operation" << endl;
}

Main.cpp

#include"Component.h"
#include"Composite.h"
#include"Leaf.h"
#include<iostream>
using namespace std;
int main() {
	Leaf* leaf = new Leaf();
	leaf->Operation();
	Composite* comp = new Composite();
	comp->addComponent(leaf);
	comp->Operation();
	Component* c = comp->getindex(0);
	c->Operation();
	return 0;
}

运行图
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值