package shiyan8; public class Adapter implements Cat,Dog{ private Cat cat=new Realcat(); private Dog dog=new Realdog(); public void setcat(Cat _cat){ cat=_cat; } public void setdog(Dog _dog){ dog=_dog; } public void zhua(){} public void wang(){} public void run(){ System.out.println("小狗学小猫:"); cat.zhua(); } public void cry(){ System.out.println("小猫学小狗:"); dog.wang(); } }
package shiyan8; public interface Cat { public void cry(); public void zhua(); }
package shiyan8; public interface Dog { public void wang(); public void run(); }
package shiyan8; public class main { public static void main(String[] args) { Dog dog=new Adapter(); Cat cat=new Adapter(); dog.run(); cat.cry(); } }
package shiyan8; public class Realcat implements Cat{ public void cry(){ System.out.println("喵喵叫!"); } public void zhua(){ System.out.println("抓老鼠!"); } }
package shiyan8; public class Realdog implements Dog{ public void wang(){ System.out.println("汪汪叫!"); } public void run(){ System.out.println("快快跑!"); } }
接下来是实验九
#include <iostream> using namespace std; class Transportation { public: virtual void drive() {} }; class Car :public Transportation { public: void drive() { cout << "小轿车"; } }; class Bus :public Transportation { public: void drive() { cout << "大巴"; } }; class Road { public: Transportation* transportation; Road(Transportation* transportation) { this->transportation = transportation; } virtual void driveOnRoad() {} }; class CementRoad :public Road { public: CementRoad(Transportation* transportation) :Road(transportation) { } void driveOnRoad() { transportation->drive(); cout << "行驶在水泥路" << endl; } }; class BituminousRoad :public Road { public: BituminousRoad(Transportation* transportation) :Road(transportation) { } void driveOnRoad() { transportation->drive(); cout << "行驶在柏油路" << endl; } }; int main() { Transportation* transportation; Car car = Car(); transportation = &car; CementRoad(transportation).driveOnRoad(); }