每日随笔——适配器模式

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

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

实验要求:

1.画出对应的类图;

2.提交源代码;

3.注意编程规范。

类图

 源码:

Cat
package sc8;

public interface cat {

    void catchMouse();
    void cry();
}
Dog
package sc8;

public interface dog {
        void wang();
        void action();

}
concreteCat
package sc8;

public class concreteCat implements cat{
    @Override
    public void catchMouse() {
        System.out.println("猫抓老鼠");
    }
    @Override
    public void cry() {
        System.out.println("猫叫");
    }
}
concreteDog
package sc8;

public class concreteDog implements dog{
    @Override
    public void wang() {
        System.out.println("狗叫");
    }
    @Override
    public void action() {
        System.out.println("狗抓老鼠");
    }
}

adapter
package sc8;

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;
    }

    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();
    }
}
test
package sc8;

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.cry();
        dog1 = (dog) A1;
        dog1.action();
    }
}

 

posted @ 2023-11-13 20:05  伽澄  阅读(27)  评论(0编辑  收藏  举报