桥接模式:将抽象部分与实现部分分离,使它们都可以独立的变化。
主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。
何时使用:实现系统可能有多个角度分类,每一种角度都可能变化。
//
// main.cpp
// bridge_pattern
//
// Created by apple on 2019/4/11.
// Copyright © 2019年 apple. All rights reserved.
//
#include <iostream>
using namespace std;
class ISport
{//运动接口
public:
virtual ~ISport() {}
virtual void do_sport(int time) = 0;
};
class run:public ISport
{//跑步类
public:
void do_sport(int time)
{
cout<<"run "<<time<<" min"<<endl;
}
};
class swim:public ISport
{//游泳类
public:
void do_sport(int time)
{
cout<<"swim "<<time<<" min"<<endl;
}
};
class fly:public ISport
{//飞行类
public:
void do_sport(int time)
{
cout<<"fly "<<time<<" min"<<endl;
}
};
class IBridge
{//桥接接口
public:
virtual ~IBridge() {}
virtual void do_sport() = 0;
};
class Client:public IBridge
{//桥接实体类,真实场景中可能存在多个桥接实体类
private:
int time;
ISport *sport = NULL;
public:
Client(int time, ISport *sport)
{
this->time = time;
this->sport = sport;
}
~Client()
{
delete sport;
sport = NULL;
}
void do_sport()
{
sport->do_sport(time);
}
};
int main(int argc, const char * argv[]) {
IBridge *bridge = NULL;
bridge = new Client(10, new run());
bridge->do_sport();
delete bridge;
bridge = new Client(8, new swim());
bridge->do_sport();
delete bridge;
bridge = new Client(6, new fly());
bridge->do_sport();
delete bridge;
return 0;
}
run 10 min
swim 8 min
fly 6 min
Program ended with exit code: 0
网友评论