烟台企业做网站,360网站seo手机优化软件,有哪些网站是用ssm做的,电脑怎样重新装wordpress文章目录 概述原理结构图代码示例 小结 概述
桥接模式(bridge pattern) 的定义是#xff1a;将抽象部分与它的实现部分分离#xff0c;使它们都可以独立地变化。
桥接模式用一种巧妙的方式处理多层继承存在的问题,用抽象关联来取代传统的多层继承,将类之间的静态继承关系转… 文章目录 概述原理结构图代码示例 小结 概述
桥接模式(bridge pattern) 的定义是将抽象部分与它的实现部分分离使它们都可以独立地变化。
桥接模式用一种巧妙的方式处理多层继承存在的问题,用抽象关联来取代传统的多层继承,将类之间的静态继承关系转变为动态的组合关系,使得系统更加灵活,并易于扩展,有效的控制了系统中类的个数 (避免了继承层次的指数级爆炸).
原理
桥接Bridge模式包含以下主要角色
抽象化Abstraction角色 主要负责定义出该角色的行为 ,并包含一个对实现化对象的引用。扩展抽象化RefinedAbstraction角色 是抽象化角色的子类实现父类中的业务方法并通过组合关系调用实现化角色中的业务方法。实现化Implementor角色 定义实现化角色的接口包含角色必须的行为和属性,并供扩展抽象化角色调用。具体实现化Concrete Implementor角色 给出实现化角色接口的具体实现。
结构图 代码示例
来看下代码示例吧如下图
// Implementor.h
#ifndef IMPLEMENTOR_H
#define IMPLEMENTOR_Hclass Implementor {
public:virtual ~Implementor() {}virtual void OperationImpl() 0;
};#endif // IMPLEMENTOR_H // ConcreteImplementorA.h
#ifndef CONCRETEIMPLEMENTORA_H
#define CONCRETEIMPLEMENTORA_H#include Implementor.hclass ConcreteImplementorA : public Implementor {
public:void OperationImpl() override {// Concrete implementation Astd::cout Concrete Implementor A std::endl;}
};#endif // CONCRETEIMPLEMENTORA_H// ConcreteImplementorB.h
#ifndef CONCRETEIMPLEMENTORB_H
#define CONCRETEIMPLEMENTORB_H#include Implementor.hclass ConcreteImplementorB : public Implementor {
public:void OperationImpl() override {// Concrete implementation Bstd::cout Concrete Implementor B std::endl;}
};// Abstraction.h
#ifndef ABSTRACTION_H
#define ABSTRACTION_H#include Implementor.hclass Abstraction {
protected:Implementor* implementor;public:Abstraction(Implementor* implementor) : implementor(implementor) {}virtual ~Abstraction() { delete implementor; }virtual void Operation() 0;
};/ RefinedAbstraction.h
#ifndef REFINEDABSTRACTION_H
#define REFINEDABSTRACTION_H#include Abstraction.hclass RefinedAbstraction : public Abstraction {
public:RefinedAbstraction(Implementor* implementor) : Abstraction(implementor) {}void Operation() override {// Refined operationstd::cout Refined Abstraction std::endl;implementor-OperationImpl();}
};/ main.cpp
#include iostream
#include Abstraction.h
#include ConcreteImplementorA.h
#include ConcreteImplementorB.h
#include RefinedAbstraction.hint main() {ConcreteImplementorA* implementorA new ConcreteImplementorA();ConcreteImplementorB* implementorB new ConcreteImplementorB();Abstraction* abstractionA new RefinedAbstraction(implementorA);Abstraction* abstractionB new RefinedAbstraction(implementorB);abstractionA-Operation();abstractionB-Operation();delete abstractionA;delete abstractionB;return 0;
}小结
上边有桥接模式的概述原理以及代码示例。看起来不错吧感兴趣可以一起学习学习。