#include "stdafx.h"
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <string>
#include <iostream>
#include <boost/format.hpp>
using namespace boost;
#define CC_SYNTHESIZE(varType, varName, funName)\
protected: varType varName;\
public: virtual varType get##funName(void) const { return varName; }\
public: virtual void set##funName(varType var){ varName = var; }
//桥接模式适用于多个对象之间
//进行多个维度的变化,组合成一个
//连接的可进行多维度变化的对象
//这里以不同的人开着不同的车在不同的道路上
//行驶为例讲解:
//抽象出道路的抽象基类
class Road
{
public:
Road(){}
virtual ~Road(){}
virtual void run() = 0;//行驶
CC_SYNTHESIZE(std::string,_m_strRoadName,RoadName);
};
//抽象出车子的抽象基类
class Car
{
public:
virtual void driver() = 0;//驾驶
CC_SYNTHESIZE(std::string,_m_strCarType,CarType);
public:
shared_ptr<Road> m_road;//road->car Road桥接到Car
};
//抽象出人物的抽象基类
class Person
{
public:
Person(){_m_strName = "XX";}
Person(const std::string& strName):_m_strName(strName){}
virtual void operation() = 0;
CC_SYNTHESIZE(std::string,_m_strName,Name);
public:
shared_ptr<Car> m_Car;//car->persion Car桥接到人
};
//具体的Road -- 普通公路
class NormalRoad : public Road
{
public:
NormalRoad(){setRoadName("普通公路");}
void run()
{
std::cout << "在" << getRoadName() << "上";
}
};
//具体的Road -- 高速公路
class SpeedRoad : public Road
{
public:
SpeedRoad(){setRoadName("高速公路");}
void run()
{
std::cout << "在" << getRoadName() << "上";
}
};
class Bike : public Car
{
public:
Bike(){setCarType("自行车");m_iSize = 2;}
void driver()
{
m_road->run();
format fmt("驾驶着%1%,车的长度为%2%米");
fmt %getCarType();
fmt %m_iSize;
std::cout << fmt.str();
}
protected:
int m_iSize;
};
class Motorbike : public Car
{
public:
Motorbike(){setCarType("摩托车");m_lId = 643363;}
void driver()
{
m_road->run();
format fmt("驾驶着%1%,车牌号为%2%");
fmt %getCarType() %m_lId;
std::cout << fmt.str();
}
protected:
long m_lId;
};
//男人
class Man : public Person
{
public:
Man(){setName("张三");}
void operation()
{
std::cout << format("一个叫%s的男人") %getName().c_str();
m_Car->driver();
std::cout << std::endl;
}
};
//女人
class Woman : public Person
{
public:
Woman(){setName("李四");}
void operation()
{
std::cout << format("一个叫%1%的女人") %getName();
m_Car->driver();
std::cout << std::endl;
}
};
void testBridgeMode()
{
shared_ptr<Road> road1 = make_shared<NormalRoad>();
shared_ptr<Road> road2 = make_shared<SpeedRoad>();
shared_ptr<Car> car1 = make_shared<Bike>();
auto car2 = make_shared<Motorbike>();
auto person1 = make_shared<Man>();
auto person2 = make_shared<Woman>();
car1->m_road = road1;
car1->driver();
car1->m_road = road2;
std::cout << std::endl;
car1->driver();
car2->m_road = road1;
std::cout << std::endl;
car2->driver();
person2->m_Car = car2;
std::cout << std::endl;
person2->operation();
person1->m_Car = car1;
person1->operation();
}
Bridge 桥接模式
最新推荐文章于 2024-06-14 02:30:26 发布