适配器模式java

[实验任务一]:双向适配器

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

 

 

 

代码按照图中顺序

package test8;

public class Adapter implements Cat,Dog{
    private Cat cat=new Realcat();
    private Dog dog=new Realdog();
    public void setcat(Cat _cat){
        cat=_cat;
    }
    public void setdog(Dog _dog){
        dog=_dog;
    }
    public void catchs(){}
    public void wang(){}
    public void run(){
        System.out.println("小狗学小猫:");
        cat.catchs();
    }
    public void miao(){
        System.out.println("小猫学小狗:");
        dog.wang();
    }
}
package test8;

public interface Cat {
    public void catchs();
    public void miao();
}
package test8;

public interface Dog {
    public void wang();
    public void run();
}
package test8;

public class Main {

    public static void main(String[] args) {
        Dog dog=new Adapter();
        Cat cat=new Adapter();
        dog.run();
        cat.miao();
    }
}
package test8;

public  class Realcat implements Cat{
    public void miao(){
        System.out.println("喵喵叫!");
    }
    public void catchs(){
        System.out.println("抓老鼠!");
    }
}
package test8;

public class Realdog implements Dog{
    public void wang(){
        System.out.println("汪汪叫!");
    }
    public void run(){
        System.out.println("跑跑跑!");
    }
}

 

 

 

posted @ 2022-10-10 09:47  zrswheart  阅读(43)  评论(0编辑  收藏  举报