大话设计模式适配器模式c++实现

适配器模式

其他二十三种设计模式

#include<iostream>

using namespace std;
//适配器模式
//Target
class Player {
    
    
public:
	Player(string _name) {
    
    
		this->name = _name;
	}
	virtual void Attack() = 0;
	virtual void Defense() = 0;

protected:
	string name;
};

class Forwards :public Player {
    
    
public:
	Forwards(string _name) :Player(_name) {
    
    }   //是Player(_name),不能是Player(name)

	virtual void Attack() {
    
    
		cout << "前锋 " << name << " 进攻" << endl;
	}
	virtual void Defense() {
    
    
		cout << "前锋 " << name << " 防守" << endl;
	}
};

class Guards :public Player {
    
    
public:
	Guards(string _name) :Player(_name){
    
    }

	virtual void Attack() {
    
    
		cout << "后卫 " << name << " 进攻" << endl;
	}
	virtual void Defense() {
    
    
		cout << "后卫 " << name << " 防守" << endl;
	}

};

//Adaptee
class ForeignCenter {
    
    
public:
	void SetName(string _name){
    
    
		this->name = _name;
	}
	string GstName() {
    
    
		return name;
	}
	void ForeignAttack() {
    
    
		cout << "外籍中锋 " << name << " 攻击" << endl;
	}
	void ForeignDefense() {
    
    
		cout << "外籍中锋 " << name << " 防守" << endl;
	}

private:
	string name;
};

//适配器类--Adapter
class Translator :public Player {
    
    
public:
	Translator(string _name):Player(_name) {
    
    
		wjzf = new ForeignCenter;
		wjzf->SetName(_name);
	}

	~Translator()
	{
    
    
		if (wjzf!=NULL)
		{
    
    
			delete wjzf;
		}
	}
	void Attack() {
    
    
		wjzf->ForeignAttack();
	}
	void Defense() {
    
    
		wjzf->ForeignDefense();
	}

private:
	ForeignCenter* wjzf;
};

void test1() {
    
    
	Player* b = new Forwards("巴蒂尔");
	b->Attack();

	Player* m = new Guards("麦迪");
	m->Attack();

	Player* Yao = new Translator("姚明");
	Yao->Attack();
	Yao->Defense();

	delete Yao;
	delete m;
	delete b;
}
int main() {
    
    
	test1();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/114144044