实验8:适配器模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解适配器模式的动机,掌握该模式的结构;
2、能够利用适配器模式解决实际问题。
[实验任务一]:双向适配器
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
实验要求:
1. 画出对应的类图;
2.提交源代码;
// 动物接口
interface Animal {
String makeSound();
String catchMouse();
}
// 猫类
class Cat implements Animal {
@Override
public String makeSound() {
return "Meow";
}
@Override
public String catchMouse() {
return "Cat is catching a mouse.";
}
}
// 狗类
class Dog implements Animal {
@Override
public String makeSound() {
return "Bark";
}
@Override
public String catchMouse() {
return "Dog cannot catch a mouse.";
}
}
// 适配器类
class Adapter implements Animal {
private Cat cat;
private Dog dog;
public Adapter(Cat cat, Dog dog) {
this.cat = cat;
this.dog = dog;
}
@Override
public String makeSound() {
// 猫学狗叫
return dog.makeSound();
}
@Override
public String catchMouse() {
// 狗学猫抓老鼠
return cat.catchMouse();
}
}
// 示例
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog = new Dog();
Adapter adapter = new Adapter(cat, dog);
// 猫叫狗的声音
System.out.println("Cat imitates dog sound: " + adapter.makeSound()); // Output: Bark
// 狗学会了抓老鼠
System.out.println("Dog imitates cat catching mouse: " + adapter.catchMouse()); // Output: Cat is catching a mouse.
}
}