实验8:适配器模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解适配器模式的动机,掌握该模式的结构;
2、能够利用适配器模式解决实际问题。
[实验任务一]:双向适配器
实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。
实验要求:
1、Cat.java
package org.example.shiyanba;
public interface Cat {
void cry();
void catchMouse();
}
2、Dog.java
package org.example.shiyanba;
public interface Dog {
void wang();
void action();
}
3、ConcreateCat.java
package org.example.shiyanba;
public class ConcreteCat implements Cat{
@Override
public void cry() {
System.out.println("猫叫");
}
@Override
public void catchMouse() {
System.out.println("猫抓老鼠");
}
}
4、ConcreateDog.java
package org.example.shiyanba;
public class ConcreteDog implements Dog{
@Override
public void wang() {
System.out.println("狗叫");
}
@Override
public void action() {
System.out.println("狗学猫捉老鼠");
}
}
5、Adapter.java
package org.example.shiyanba;
public class Adapter implements Dog,Cat{
private Cat cat;
private Dog dog;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public void cry() //猫学狗叫
{
System.out.print( "猫学");
dog.wang();
}
@Override
public void catchMouse() {
cat.catchMouse();
}
@Override
public void wang() {
dog.wang();
}
@Override
public void action() //狗学猫抓老鼠
{
System.out.print( "狗学");
cat.catchMouse();
}
}
6、Test.java
package org.example.shiyanba;
public class Test {
public static void main(String args[])
{
Cat cat1 = new ConcreteCat();
Dog dog1 = new ConcreteDog();
Adapter A1 = new Adapter();
A1.setCat(cat1);
A1.setDog(dog1);
cat1 = (Cat) A1;
cat1.catchMouse();
cat1.cry();
dog1 = (Dog) A1;
dog1.action();
}
}
标签:11.5,void,dog,Dog,Cat,Override,public From: https://www.cnblogs.com/zzqq1314/p/18545031