适配器模式--Java实现
画类图
设计一个双向适配器,让猫也能学狗叫,够也能学猫抓老鼠
具体代码实现
//Cat.java
package org.example.design006;
public interface Cat {
public void miao();
public void zhua();
}
//Dog.java
package org.example.design006;
public interface Dog {
public void wang();
public void run();
}
//RealCat.java
package org.example.design006;
public class RealCat implements Cat{
@Override
public void miao() {
System.out.println("喵喵叫");
}
@Override
public void zhua() {
System.out.println("抓老鼠");
}
}
//RealDog.java
package org.example.design006;
public class RealDog implements Dog{
@Override
public void wang() {
System.out.println("汪汪叫");
}
@Override
public void run() {
System.out.println("遍地跑");
}
}
//Adapter.java
package org.example.design006;
public class Adapter implements Cat,Dog{
public void setCat(Cat cat) {
this.cat = cat;
}
public void setDog(Dog dog) {
this.dog = dog;
}
private Cat cat=new RealCat();
private Dog dog=new RealDog();
@Override
public void miao() {
System.out.println("小猫学狗叫:");
dog.wang();
}
@Override
public void zhua() {
System.out.println("小猫学小狗:");
dog.run();
}
@Override
public void wang() {
System.out.println("小狗学猫叫:");
cat.miao();
}
@Override
public void run() {
System.out.println("小狗学小猫:");
cat.zhua();
}
}
//Main.java
package org.example.design006;
public class Main {
public static void main(String[] args) {
Cat cat=new Adapter();
Dog dog=new Adapter();
cat.zhua();
dog.run();
cat.miao();
dog.wang();
}
}