实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
public class Client { public static void main(String[] args) { Adapter adapter = new Adapter(); adapter.setCatAdapter(new ConcreteCat()); Dog dog = adapter; dog.wang(); adapter.setDogAdapter(new ConcreteDog()); Cat cat = adapter; cat.catchMouse(); } } public interface Dog { void wang(); } public class ConcreteDog implements Dog { @Override public void wang() { System.out.println("狗汪汪叫"); } } public interface Cat { void catchMouse(); } public class ConcreteCat implements Cat { @Override public void catchMouse() { System.out.println("猫抓老鼠"); } } public class Adapter implements Dog, Cat { private Dog dog; private Cat cat; public void setDogAdapter(Dog dog) { this.dog = dog; } public void setCatAdapter(Cat cat) { this.cat = cat; } @Override public void catchMouse() { System.out.print("猫学会了"); dog.wang(); } @Override public void wang() { System.out.print("狗学会了"); cat.catchMouse(); } }
标签:适配器,dog,模式,cat,public,Dog,Cat,void From: https://www.cnblogs.com/tk203/p/16787257.html