10.28日报

今天完成了设计模式的实验,以下为今天的实验内容:

实验8:适配器模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解适配器模式的动机,掌握该模式的结构;

2、能够利用适配器模式解决实际问题。

 
   

 

 

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

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

实验要求:

1.  画出对应的类图;

 

2.提交源代码;

// 动物接口
interface Animal {
    void makeSound();
    void hunt();
}

// 猫类
class Cat implements Animal {
    public void makeSound() {
        System.out.println("喵");
    }

    public void hunt() {
        System.out.println("猫在抓老鼠");
    }
}

// 狗类
class Dog implements Animal {
    public void makeSound() {
        System.out.println("汪");
    }

    public void hunt() {
        System.out.println("狗不抓老鼠");
    }
}

// 猫到狗的适配器
class CatToDogAdapter implements Animal {
    private Cat adaptee;

    public CatToDogAdapter(Cat cat) {
        this.adaptee = cat;
    }

    public void makeSound() {
        System.out.println("喵喵(模仿汪汪叫)");
    }

    public void hunt() {
        System.out.println("猫在模仿狗不抓老鼠");
    }
}

// 狗到猫的适配器
class DogToCatAdapter implements Animal {
    private Dog adaptee;

    public DogToCatAdapter(Dog dog) {
        this.adaptee = dog;
    }

    public void makeSound() {
        System.out.println("汪汪(模仿喵喵叫)");
    }

    public void hunt() {
        System.out.println("狗在模仿猫抓老鼠");
    }
}

// 测试类
public class AdapterTest {
    public static void main(String[] args) {
        Animal cat = new Cat();
        Animal dog = new Dog();

        Animal catAdapter = new CatToDogAdapter(new Cat());
        Animal dogAdapter = new DogToCatAdapter(new Dog());

        cat.makeSound();
        dog.makeSound();

        catAdapter.makeSound();
        dogAdapter.makeSound();

        cat.hunt();
        dog.hunt();

        catAdapter.hunt();
        dogAdapter.hunt();
    }
}

 

3.注意编程规范。

posted @ 2024-11-27 10:25  Code13  阅读(7)  评论(0)    收藏  举报