软考------(抽象类、接口) 策略设计模式(strategy) 应用
某软件公司现欲开发一款飞机飞行模拟系统,该系统主要模拟不同种类飞机的飞行特征与起飞特征。需要模拟的飞机种类及其特征如表5-1所示。
#include <iostream> #include <string> using namespace std; class FlyBehavior { public: virtual void fly31()=0; }; class SubSonicFly:public FlyBehavior { public: void fly31() {cout<<"亚音速飞行"<<endl;} }; class SuperSonicFly:public FlyBehavior { public: void fly31() {cout<<"超音速飞行"<<endl;} }; class TakeOffBehavior { public: virtual void takeoff31()=0; }; class VerticalTakeOff:public TakeOffBehavior { public: void takeoff31() {cout<<"垂直起飞"<<endl;} }; class LongDistanceTakeOff:public TakeOffBehavior { public: void takeoff31() {cout<<"长距离起飞"<<endl;} }; class AirCraft { protected: FlyBehavior *flyBehavior; TakeOffBehavior *takeOffBehavior; public: void fly31() {flyBehavior->fly31();} void takeoff31() {takeOffBehavior->takeoff31();} }; class Helicopter:public AirCraft { public: Helicopter() { flyBehavior=new SubSonicFly(); takeOffBehavior=new VerticalTakeOff(); } ~Helicopter() { if(!flyBehavior) delete flyBehavior; if(!takeOffBehavior) delete takeOffBehavior; } }; int main() { Helicopter *x=new Helicopter(); x->fly31(); x->takeoff31(); return 0; }
运行结果:
java 代码实现:
interface FlyBehavior { public void fly31(); } class SubSonicFly implements FlyBehavior { public void fly31() {System.out.println("亚音速飞行");} } class SuperSonicFly implements FlyBehavior { public void fly31() {System.out.println("超音速飞行");} } interface TakeOffBehavior { public void takeoff31(); } class VerticalTakeOff implements TakeOffBehavior { public void takeoff31() {System.out.println("垂直起飞");} } class LongDistanceTakeOff implements TakeOffBehavior { public void takeoff31() {System.out.println("长距离起飞");} } class AirCraft { protected FlyBehavior flyBehavior; protected TakeOffBehavior takeOffBehavior; public void fly31() {flyBehavior.fly31();} public void takeoff31() {takeOffBehavior.takeoff31();} } class Helicopter extends AirCraft { public Helicopter() { flyBehavior=new SubSonicFly(); takeOffBehavior=new VerticalTakeOff(); } } public class dev { public static void main(String [] args) { Helicopter x=new Helicopter(); x.fly31(); x.takeoff31(); } }
本博客是博主个人学习时的一些记录,不保证是为原创,个别文章加入了转载的源地址,还有个别文章是汇总网上多份资料所成,在这之中也必有疏漏未加标注处,如有侵权请与博主联系。
如果未特殊标注则为原创,遵循 CC 4.0 BY-SA 版权协议。
posted on 2017-01-30 16:02 Angry_Panda 阅读(744) 评论(0) 编辑 收藏 举报