11.4

 

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

实验要求:

1.画出对应的类图;

2.提交源代码;

3.注意编程规范。

 

类图:

 

 

源代码:

接口

public interface Cat {

  void cry();

  void catchMouse();

}

 

Cat类

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

    }

}

}

 

Test测试类

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 on 2024-11-04 22:27  HA_wind  阅读(2)  评论(0编辑  收藏  举报

导航