双向适配器

 

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

实验要求:

1.  画出对应的类图;

 

2.  提交源代码;

public interface Cat {

  void cry();

  void catchMouse();

}

public class ConcreteCat implements Cat{

    @Override

    public void cry() {

        System.out.println("猫叫");

    }

    @Override

    public void catchMouse() {

        System.out.println("猫抓老鼠");

    }

}

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();

    }

}

}

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();

    }

}

posted @ 2024-11-05 14:08  涨涨涨张  阅读(4)  评论(0编辑  收藏  举报