适配器模式双向适配器

今天做了双向适配器的实验,花了两个小时的时间,最终成功运行程序,也了解了双向适配器模式的优点和双向适配器的模式原理。

下面是要求以及我做实验的步骤:

要求:

实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠

1. 画出对应的类图;

代码部分:

public class adpter implements Cat,Dog {

Cat cat;
Dog dog;

public adpter(Cat cat, Dog dog) {
this.cat = cat;
this.dog = dog;
}

public adpter(Cat cat){
this.cat=cat;
}
public adpter(Dog dog){
this.dog=dog;
}

@Override
public void Catcay() {
dog.DogCay();
}

@Override
public void DogCay() {
cat.Catcay();
}
}

public interface Cat {
public void Catcay();
}

public interface Dog {
public void DogCay();
}

public class main {

public static void main(String[] args) {

Cat cat = new adpter(new sanny());

cat.Catcay();

Dog dog=new adpter(new Tom());
dog.DogCay();
}

}

public class sanny implements Dog {
@Override
public void DogCay() {
System.out.println("汪汪汪。。。。。");
}
}

public class Tom implements Cat {
@Override
public void Catcay() {
System.out.println("喵喵喵。。。。。");
}
}

原文地址:https://www.cnblogs.com/092e/p/15543127.html