您的位置:首页 > 编程语言 > C语言/C++

两人合作审阅C++装饰模式

2016-04-21 21:24 375 查看
<span style="font-family: Arial, Helvetica, sans-serif;">#pragma once</span>
#include<iostream>
#include<string>
using namespace std;

class Ship
{
public:
virtual void run() = 0;
virtual void shot() = 0;
};

class NorthCarolina :public Ship
{
public:
void run() { cout << "NorthCarolina is running." << endl; };
void shot() { cout << "NorthCarolina is shotting." << endl; };
};

class Iowa :public Ship
{
public:
void run() { cout << "Iowa is running." << endl; };
void shot() { cout << "Iowa is shotting." << endl; };
};

class Decorator :public Ship
{
public:
Decorator(Ship* ship) :ship(ship) {};
void run() { ship->run(); }
void shot() { ship->shot(); }
protected:
Ship* ship;
};

class ScoutPlane :public Decorator
{
string scout;
public:
ScoutPlane(Ship* ship) :Decorator(ship) {}
void setScout() { scout = "Searching......"; };
void getScout() { cout << scout << endl; }
void run() {
ship->run();
setScout();
getScout();
}
void shot() {
ship->shot();
}
};

class Ammu :public Decorator
{
string ammu;
public:
Ammu(Ship* ship) :Decorator(ship) {}
void setAmmu() { ammu = "AP"; };
void getAmmu() { cout << "shotting " << ammu << "." << endl; }
void run() {
ship->run();
}
void shot() {
ship->shot();
setAmmu();
getAmmu();
}
};
<pre name="code" class="cpp">#include"header.h"
using namespace std;

int main()
{
Ship* ship1(new Iowa);
Ship* ship2(new NorthCarolina);
ship1->run();
ship1->shot();
cout << "----------------" << endl;
ship2->run();
ship2->shot();
cout << "----------------" << endl;
Ship* ship3(new Ammu(ship1));
ship3->run();
ship3->shot();
cout << "----------------" << endl;
Ship* ship4(new ScoutPlane(ship3));
ship4->run();
ship4->shot();
cout << "----------------" << endl;
Ship* ship5(new ScoutPlane(ship2));
ship5->run();
ship5->shot();
system("pause");
return 0;
}
练习使用C++装饰模式,代码并不是很难,所以没有加注释。
已经全部检查过,编译通过,主要就是理解装饰模式是如何一层一层的把需求加到对象身上。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: