适配器模式

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

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

实验要求:

1. 画出对应的类图;

 

2.提交源代码;

public interface CatTarget {

    public abstract void catchMouse();

}

public class ConcreteCatTarget implements CatTarget {

    @Override

    public void catchMouse() {

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

    }

}

 

public interface DogAdaptee {

    public abstract void cry();

}

public class ConcreteDogAdaptee implements DogAdaptee {

    @Override

    public void cry() {

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

    }

}

 

public class Adapter implements CatTarget,DogAdaptee {

 

    private CatTarget catTarget;

    private DogAdaptee dogAdaptee;

 

    public Adapter() {

    }

 

    public void setCatTarget(CatTarget catTarget) {

        this.catTarget = catTarget;

    }

 

    public void setDogAdaptee(DogAdaptee dogAdaptee) {

        this.dogAdaptee = dogAdaptee;

    }

 

    public void catchMouse() {

        System.out.print("猫学狗叫,即目标类调用适配者中的方法:");

        dogAdaptee.cry();

 

    }

 

    public void cry(){

        System.out.print("狗学猫抓老鼠,即适配者调用目标类中的方法:");

        catTarget.catchMouse();

    }

 

}

 

public class Client {

    public static void main(String[] args) {

        //适配器

        Adapter adapter = (Adapter) XMLUtils.getBean("adapterPattern");

 

        //目标类通过适配器调用适配者方法

        CatTarget concreteCatTarget = (ConcreteCatTarget) XMLUtils.getBean("adapterPatternTarger");

        adapter.setCatTarget(concreteCatTarget);

        adapter.cry();

 

        //适配者通过适配器调用目标类方法

        DogAdaptee concreteDogAdaptee = (ConcreteDogAdaptee) XMLUtils.getBean("adapterPatternAdaptee");

        adapter.setDogAdaptee(concreteDogAdaptee);

        adapter.catchMouse();

    }

}

posted @ 2021-10-08 23:13  Zwyooo  阅读(164)  评论(0编辑  收藏  举报