某软件公司现欲开发一款飞机飞行模拟系统,该系统主要模拟不同种类飞机的飞行特征与起飞特征。需要模拟的飞机种类及其特征如表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(); } }