赞
踩
定义:把抽象部分和它的实现部分分离,使得它们都可以独立的变化
栗子场景:华山派和崆峒派先后获得了武林秘籍辟邪剑谱和九阴真经,于是开始苦练此功..
UML类图
代码:
- #include<iostream>
-
- using namespace std;
- class Sects;
-
- //功夫
- class Kungfu
- {
- public:
- virtual void practice() = 0;
- };
-
- //九阴真经
- class JiuyinZj :public Kungfu
- {
- public:
- virtual void practice()
- {
- cout << "@九阴真经。注:玄门内功,至阴至柔" << endl;
- }
- };
-
- //辟邪剑谱
- class PixieJp :public Kungfu
- {
- public:
- virtual void practice()
- {
- cout << "@辟邪剑谱,注:欲练此功,必先自宫" << endl;
- }
- };
-
-
- //门派
- class Sects{
- public:
- Sects() :m_kungfu(nullptr){}
-
- void setMartialarts(Kungfu* m)
- {
- this->m_kungfu = m;
- }
- Kungfu* getKungfu()
- {
- return m_kungfu;
- }
- virtual void practice() = 0;
- private:
- Kungfu *m_kungfu; //桥接
- };
-
- //华山
- class HuaShan :public Sects
- {
- public:
- void practice()
- {
- getKungfu()->practice();
- }
- };
-
- //崆峒
- class KongTong :public Sects
- {
- public:
- void practice()
- {
- getKungfu()->practice();
- }
- };
-
- //客户端
- int main()
- {
- Sects *sects = new HuaShan;
- cout << "华山派弟子正在练习:" << endl;
- sects->setMartialarts(new JiuyinZj);
- sects->practice();
-
- sects->setMartialarts(new PixieJp);
- sects->practice();
-
- sects = new KongTong;
- cout << "崆峒派弟子正在练习:" << endl;
- sects->setMartialarts(new JiuyinZj);
- sects->practice();
-
- sects->setMartialarts(new PixieJp);
- sects->practice();
- if (sects)
- {
- delete sects;
- sects = nullptr;
- }
-
- return 0;
- }
效果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。