跟装饰器模式一样,设计上属于职责划分,要划清责任,分清主体和拓展,解决的是(随着需求变化,子类数目极具膨胀的问题)
头文件
#pragma once
#include <iostream>
using namespace std;
template<typename T>
class My_character;
template<typename T>
class My_weapons {
public:
virtual void fire() {}
};
template<typename T>
class weapons_gun:public My_weapons<T>{
public:
virtual void fire() {
cout << "武器:火枪 对目标造成伤害" << endl;
}
};
template<typename T>
class weapons_knife :public My_weapons<T> {
public:
virtual void fire() {
cout << "武器:军刀 对目标造成伤害" << endl;
}
};
template<typename T>
class weapons_rocket :public My_weapons<T> {
public:
virtual void fire() {
cout << "武器:火箭 对目标造成伤害" << endl;
}
};
template<typename T>
class My_character {
public:
My_character(My_weapons<T>* Weapon) :wea(Weapon) {}
My_weapons<T>* wea;
virtual void attack(My_character<T>* target) {
wea->fire();
}
};
template<typename T>
class My_soldier :public My_character<T> {
public:
My_soldier(My_weapons<T>* Weapon) :My_character<T>(Weapon) {}
};
template<typename T>
class My_enemy :public My_character<T> {
public:
My_enemy(My_weapons<T>* Weapon) :My_character<T>(Weapon) {}
};
接口
cout << "测试桥模式" << endl;
weapons_gun<int>* gun1 = new weapons_gun<int>();
My_soldier<int>* soldier1 = new My_soldier<int>(gun1);
weapons_knife<int>* knife1 = new weapons_knife<int>();
My_soldier<int>* soldier2 = new My_soldier<int>(knife1);
weapons_rocket<int>* rocket1 = new weapons_rocket<int>();
My_soldier<int>* soldier3 = new My_soldier<int>(rocket1);
weapons_gun<int>* gun2 = new weapons_gun<int>();
My_enemy<int>* enemy1 = new My_enemy<int>(gun2);
weapons_knife<int>* knife2 = new weapons_knife<int>();
My_enemy<int>* enemy2 = new My_enemy<int>(knife2);
weapons_rocket<int>* rocket2 = new weapons_rocket<int>();
My_enemy<int>* enemy3 = new My_enemy<int>(rocket2);
soldier1->attack(enemy1);
soldier2->attack(enemy2);
soldier3->attack(enemy3);
|