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

<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++装饰模式,代码并不是很难,所以没有加注释。
已经全部检查过,编译通过,主要就是理解装饰模式是如何一层一层的把需求加到对象身上。
 
 

转载于:https://www.cnblogs.com/fhiutc/p/5474990.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值