设计模式-桥接模式
桥接模式
BridgeModle.h
#pragma once
#include <iostream>
using namespace std;
class Tool {
public:
Tool(){}
Tool(string str){}
virtual string usingTool()=0;
virtual string getProperty() = 0;
private:
};
class Knife : public Tool
{
public:
Knife(){}
Knife(string str) { cout << "战刀" << str << endl; }
string usingTool() {
//cout << "大砍刀" << endl;
string str = "青龙偃月刀";
return str;
}
virtual string getProperty() {
string str = "一流刀法";
return str;
}
};
class Machine {
public:
Machine(){}
Machine(string str){}
virtual string usingMachine() = 0;
virtual string getProperty() = 0;
};
class Horse : public Machine
{
public:
Horse(){}
Horse(string str) { cout << "战马" << str << endl; }
//(string horse, string knife, Person *person)
string usingMachine() {
//cout << "赤兔马" << endl;
string str = "赤兔马";
return str;
}
virtual string getProperty() {
string str = "神马";
return str;
}
private:
};
class Person{
public:
Person(){}
Person(string str){}
Person(Machine *h, Tool *t, Person *p){}
virtual void onWar(const string horse, const string knife, const string onWar) = 0;
virtual string print_name() = 0;
virtual void getProperty() = 0;
private:
Machine *m_machine;
Tool *tool;
};
class Guanyu : public Person
{
public:
Guanyu(){}
Guanyu(string str) { }
Guanyu(Machine *h, Tool *t, Person *p) {
m_machine = h; m_tool = t;
string str1 = h->usingMachine();
string str2 = t->usingTool();
string str3 = p->print_name();
onWar(str1, str2, str3);
}
virtual void onWar(const string horse, const string knife, const string person) {
cout << "关羽骑" <</*赤兔马*/horse << "手拿"<</*青龙偃月刀*/knife << "去斩" << person << endl;
}
virtual string print_name() {
string str = "关羽";
return str;
}
virtual void getProperty() {
cout << "关羽骑的是" << this->m_machine->getProperty() << "用的是" << this->m_tool->getProperty()<<endl;
}
private:
Machine *m_machine;
Tool *m_tool;
};
class HuaXiong : public Person
{
public:
HuaXiong(){}
HuaXiong(string str){ }
HuaXiong(Machine *h, Tool *t, Person *p) {
m_machine = h; m_tool = t;
onWar(h->usingMachine(), t->usingTool(), p->print_name());
}
virtual void onWar(const string horse, const string knife, const string person) {
cout << "华雄骑"<</*赤兔马*/horse << "手拿"<</*青龙偃月刀*/knife << "去斩" << person << endl;
}
virtual string print_name() {
string str = "华雄";
return str;
}
virtual void getProperty() {
cout << "华雄骑的是" << this->m_machine->getProperty() << "用的是" << this->m_tool->getProperty()<<endl;
}
private:
Machine *m_machine;
Tool *m_tool;
};
main.cpp
int main(){
Person*p1 = new Guanyu(new Horse("赤兔马"), new Knife("青龙偃月刀"), new HuaXiong("华雄"));
p1->getProperty();
Person *p2 = new HuaXiong(new Horse("赤兔马"), new Knife("青龙偃月刀"), new Guanyu("关羽"));
p2->getProperty();
return 0;
}
输出
战刀青龙偃月刀
战马赤兔马
关羽骑赤兔马手拿青龙偃月刀去斩华雄
关羽骑的是神马用的是一流刀法
战刀青龙偃月刀
战马赤兔马
华雄骑赤兔马手拿青龙偃月刀去斩关羽
华雄骑的是神马用的是一流刀法