标签:
// Design Pattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> #include <vector> using namespace std; //人物基类 class Character { public: virtual void Attack() = 0; }; //男人物 class MaleCharacter : public Character { public: virtual void Attack() = 0; }; //女人物 class FemaleCharacter : public Character { public: virtual void Attack() = 0; }; //男刀客 class PhysicalMaleChar : public MaleCharacter { public: virtual void Attack() { cout << "男角色: 物理攻击" << endl; } }; //女刀客 class PhysicalFemaleChar : public FemaleCharacter { public: virtual void Attack() { cout << "女角色: 物理攻击" << endl; } }; //男法师 class MagicMaleChar : public MaleCharacter { public: virtual void Attack() { cout << "男角色: 法术攻击" << endl; } }; //女法师 class MagicFemalChar : public FemaleCharacter { public: virtual void Attack() { cout << "女角色: 法术攻击" << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { Character* character = new MagicFemalChar(); character->Attack(); system("pause"); return 0; }结果:
// Design Pattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> #include <vector> using namespace std; //属性基类,相当于Implement类 class Attribute { public: virtual void Attack() = 0; }; //人物基类,相当于UML图中的Abstract类 class Character { protected: //保存一个属性的指针 Attribute* m_Attribute; public: //设置属性(职业) void SetAttribute(Attribute* attribute) { m_Attribute = attribute; } //攻击接口 virtual void Attack() = 0; }; //男人物 class MaleCharacter : public Character { public: virtual void Attack() override { cout << "男角色: "; m_Attribute->Attack(); } }; //女人物 class FemaleCharacter : public Character { public: virtual void Attack() override { cout << "女角色: "; m_Attribute->Attack(); } }; //物理属性 class PhysicalAttribute : public Attribute { public: void Attack() override { cout << "物理攻击" << endl; } }; //法系属性 class MagicAttribute : public Attribute { public: void Attack() override { cout << "法系攻击" << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { Character* character = new FemaleCharacter(); Attribute* magicAttribute = new MagicAttribute(); character->SetAttribute(magicAttribute); character->Attack(); system("pause"); return 0; }结果:
标签:
原文地址:http://blog.csdn.net/puppet_master/article/details/51345537