10.28日总结

一、问题描述

  设计和实现一个双向适配器实例,使得猫Cat可以学狗Dog叫Cry(),狗可以学猫抓老鼠CatchMouse(),设计类图并编程实现。

1.类图

2.源代码

1.Cat接口:

 

public interface Cat {

  void cry();

  void catchMouse();

}

2.实体Cat类(另一个类似):

 

public class ConcreteCat implements Cat{

    @Override

    public void cry() {

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

    }

    @Override

    public void catchMouse() {

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

    }

}

 

3. Dog接口

public interface Dog {

    void wang(); // 狗叫的方法

    void action(); // 狗学猫抓老鼠的方法,这里假设是Dog接口中新增的方法

}

 

 4.实体Dog类

public class ConcreteDog implements Dog {

    @Override

    public void wang() {

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

    }

 

    @Override

    public void action() {

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

    }

}

 

5.适配器类:

 

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

    }

}

}

6.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-05 14:28  Mini-Q  阅读(1)  评论(0编辑  收藏  举报