实验8:适配器模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解适配器模式的动机,掌握该模式的结构;
2、能够利用适配器模式解决实际问题。
[实验任务一]:双向适配器
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
实验要求:
1. 画出对应的类图;
```mermaid
classDiagram
class Animals {
<<interface>>
+shout()
+move()
}
class Cat {
+catches()
}
class Dog {
+wang()
}
class CatAdapter {
+shout()
+move()
}
class DogAdapter {
+shout()
+move()
}
Animals <|.. CatAdapter
Animals <|.. DogAdapter
Cat <|-- CatAdapter
Dog <|-- DogAdapter
```
2. 提交源代码;
|
|
|
|
|
|
|
|
|
|
|
|
package Tutorial08;
public interface Animals {
public void shout();
public void move();
}
|
|
|
|
|
package Tutorial08;
public class Cat {
public void catches(){
System.out.println("抓老鼠");
}
}
|
|
|
|
|
package Tutorial08;
public class Dog {
public void wang(){
System.out.println("汪汪叫");
}
}
|
|
|
|
|
package Tutorial08;
public class CatAdapter extends Cat implements Animals{
@Override
public void shout() {
}
@Override
public void move() {
System.out.print("狗砸:");
super.catches();
}
}
|
|
|
|
|
package Tutorial08;
public class DogAdapter extends Dog implements Animals{
@Override
public void shout() {
System.out.print("哈吉咪:");
super.wang();
}
@Override
public void move() {
}
}
|
|
|
|
|
package Tutorial08;
import com.sun.xml.internal.ws.util.xml.XmlUtil;
public class Main {
public static void main(String[]
args) {
DogAdapter dogAdapter = new
DogAdapter();
CatAdapter catAdapter = new
CatAdapter();
dogAdapter.shout();
System.out.println("--------------------");
catAdapter.move();;
}
}
|
|
3.注意编程规范。