结构性模式 :关注如何将现有类或对象组织在一起形成更加强大的结构【对象结构性模式】
定义:
- 将抽象部分与它的实现部分解耦,使得两者都能够独立变化。
- 又称:柄体模式(Handle and Body)或接口模式(Interface)
- 用抽象关联取代了传统的多层继承
- 将类之间的静态继承关系转化成动态的对象组合关系
适用环境:
- 需要在抽象化和具体化之间增加更多的灵活性,避免在两个层次之间建立静态的继承关系
- 抽象部分和实现部分可以以继承的方式独立扩展而互不影响
- 一个类存在两个(或多个)独立变化的维度,且这两个(或多个)维度都需要独立地进行扩展
- 不希望使用继承或因为多层继承导致系统类的个数急剧增加的系统
模式优点:
- 分离抽象接口及其实现部分
- 可以取代多层继承方案,极大地减少了子类的个数
- 提高了 系统的可扩展性,在两个变化维度中任意扩展一个维度,不需要修改原有系统,符合开闭原则
模式缺点:
- 会增加系统的理解和设计难度,由于关联关系建立在抽象层,需要开发者一开始就针对抽象层进行设计和编程
- 正确识别出系统中两个独立变化的维度并不是一件容易的事情
类图
代码:
#include <iostream>
class Implement{
public:
virtual void OperationImlp() = 0;
};
class ConcreteImplementA:public Implement{
public:
void OperationImlp(){ std::cout << "This is A" << std::endl;}
};
class ConcreteImplementB:public Implement{
public:
void OperationImlp(){ std::cout << "This is B" << std::endl;}
};
class Abstraction{
public:
virtual void Operation(Implement *implement) = 0;
};
class RefinedAbstraction:public Abstraction{
public:
void Operation(Implement *implement){ implement->OperationImlp();}
};
int main(){
Implement *implement1 = new ConcreteImplementA();
Implement *implement2 = new ConcreteImplementB();
Abstraction *abstraction = new RefinedAbstraction();
abstraction->Operation(implement1);
abstraction->Operation(implement2);
return 0;
}
运行结果:
This is A
This is B
例子:
代码:
#include <iostream>
#include <string>
class Color{
public:
virtual void drawColor() = 0;
};
class Red:public Color{
void drawColor(){ std::cout << "Red" << std::endl;}
};
class Green:public Color{
void drawColor(){ std::cout << "Green" <<std::endl;}
};
class Blue:public Color{
void drawColor(){ std::cout << "Blue" << std::endl;}
};
class Pan{
protected:
Color *color;
public:
void setColor(Color *color){this->color = color;}
virtual void draw() = 0;
};
class BigPan:public Pan{
public:
void draw(){
std::cout << "This is BigPan" << "\t" << "Color:" ;
this->color->drawColor();
}
};
class MiddlePan:public Pan{
void draw(){
std::cout << "This is MiddlePan" << "\t" << "Color:" ;
this->color->drawColor();
}
};
class SmailPan:public Pan{
void draw(){
std::cout << "This is SmailPan" << "\t" << "Color:" ;
this->color->drawColor();
}
};
int main(){
Color *color = new Red();
Pan *pan = new BigPan();
pan->setColor(color);
pan->draw();
/* 运行结果:This is BigPan Color:Red */
color = new Green();
pan = new BigPan();
pan->setColor(color);
pan->draw();
/* 运行结果:This is BigPan Color:Green */
color = new Blue();
pan = new BigPan();
pan->setColor(color);
pan->draw();
/* 运行结果:This is BigPan Color:Blue */
color = new Blue();
pan = new MiddlePan();
pan->setColor(color);
pan->draw();
/* 运行结果:This is MiddlePan Color:Blue */
}
桥接模式与适配器模式的联用
- 桥接模式:用于系统的初步设计,对于存在两个独立变化维度的类可以将其分为抽象化和实现化两个角色,使他们可以分别进行变化
- 适配器模式:当发现系统与已有类无法协同工作时