[实验任务一]:双向适配器
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
Animal.java
// 动物接口 interface Animal { void makeSound(); void catchMouse(); }
AnimalAdapter.java
// 双向适配器 class AnimalAdapter implements Animal { private Animal animal; public AnimalAdapter(Animal animal) { this.animal = animal; } @Override public void makeSound() { animal.makeSound(); } @Override public void catchMouse() { animal.catchMouse(); } }
Cat.java
// 猫类 class Cat implements Animal { @Override public void makeSound() { System.out.println("猫叫:喵喵喵"); } @Override public void catchMouse() { System.out.println("猫抓老鼠"); } }
Dog.java
// 狗类 class Dog implements Animal { @Override public void makeSound() { System.out.println("狗叫:汪汪汪"); } @Override public void catchMouse() { System.out.println("狗学会了猫抓老鼠"); } }
Main.java
// 测试代码 public class Main { public static void main(String[] args) { Cat cat = new Cat(); Dog dog = new Dog(); // 猫变成狗 Animal dogAdapter = new AnimalAdapter(cat); dogAdapter.makeSound(); // 输出:猫叫:喵喵喵 dogAdapter.catchMouse(); // 输出:猫抓老鼠 // 狗变成猫 Animal catAdapter = new AnimalAdapter(dog); catAdapter.makeSound(); // 输出:狗叫:汪汪汪 catAdapter.catchMouse(); // 输出:狗学会了猫抓老鼠 } }
类图
标签:makeSound,报告,void,Animal,Override,今日,catchMouse,public From: https://www.cnblogs.com/zjq164/p/17811797.html