2024.11.4(周一)

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

实验要求:

1.画出对应的类图;

2.提交源代码;

3.注意编程规范。

1、类图

 

 

2、源代码

(1)Adapter.java

package shiyan8;

 

public class Adapter implements Cat,Dog{

    private Cat cat=new Realcat();

    private Dog dog=new Realdog();

    public void setcat(Cat _cat){

        cat=_cat;

    }

    public void setdog(Dog _dog){

        dog=_dog;

    }

    public void zhua(){}

    public void wang(){}

    public void run(){

        System.out.println("小狗学小猫:");

        cat.zhua();

    }

    public void cry(){

        System.out.println("小猫学小狗:");

        dog.wang();

    }

}

(2)Cat.java

package shiyan8;

 

public interface Cat {   

    public void cry();

    public void zhua();

}

 

(3)Main.java

package shiyan8;

 

public class main {

 

    public static void main(String[] args) {

        Dog dog=new Adapter();

        Cat cat=new Adapter();

        dog.run();

        cat.cry();

    }

}

(4)Dog.java

package shiyan8;

 

public interface Dog {

    public void wang();

    public void run();

}

(5)Realcat.java

package shiyan8;

 

public class Realcat implements Cat{

    public void cry(){

        System.out.println("喵喵叫!");

    }

    public void zhua(){

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

    }

}

(6)Realdog.java

package shiyan8;

 

public class Realdog implements Dog{

    public void wang(){

        System.out.println("汪汪叫!");

    }

    public void run(){

        System.out.println("不抓老鼠!");

    }

}

posted @ 2024-11-11 07:50  记得关月亮  阅读(0)  评论(0编辑  收藏  举报