实验8:适配器模式

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

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

实验要求:

1. 对应的类图:

 

2. 源代码:

Cat接口:

 

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 @ 2024-11-04 09:22  艾鑫4646  阅读(10)  评论(0编辑  收藏  举报