问题描述:
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
类图:
Java代码:
//Cat.java package shiyan8; public interface Cat { public void cry(); public void zhua(); } //Dag.java package shiyan8; public interface Dog { public void wang(); public void run(); } //Realcat.java package shiyan8; public class Realcat implements Cat{ public void cry(){ System.out.println("喵喵叫!"); } public void zhua(){ System.out.println("抓老鼠!"); } } //Realdog.java package shiyan8; public interface Dog { public void wang(); public void run(); } //Adapter.java 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(); } } //main.java package shiyan8; public class main { public static void main(String[] args) { Dog dog=new Adapter(); Cat cat=new Adapter(); dog.run(); cat.cry(); } }
运行结果: