适配器模式和桥接模式代码

适配器模式和桥接模式代码
适配器模式

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


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



package test8;
interface Cat { void catchMouse(); } package test8; interface Dog { void bark(); }
package test8;

// 具体的猫类
class RealCat implements Cat {
    @Override
    public void catchMouse() {
        System.out.println("抓老鼠!");
    }
}


package test8;

// 具体的狗类
class RealDog implements Dog {
    @Override
    public void bark() {
        System.out.println("汪汪汪!");
    }
}
package test8;

class Adapter implements Dog, Cat {
    private Dog dog;
    private Cat cat;

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    @Override
    public void bark() {
        System.out.println("狗学");
        cat.catchMouse();
    }

    @Override
    public void catchMouse() {
        System.out.println("猫学");
        dog.bark();
    }
}
package test8;

public class Main {
    public static void main(String[] args) {
        Dog dog = new RealDog(); // 确保创建一个 RealDog 对象
        Cat cat = new RealCat(); // 确保创建一个 RealCat 对象

        Adapter adapter = new Adapter();
        adapter.setCat(cat);
        adapter.setDog(dog);

        adapter.bark(); // 狗抓老鼠
        adapter.catchMouse(); // 猫学狗抓老鼠
    }
}

桥接模式代码:

[实验任务一]:两个维度的桥接模式

用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。

package test9;

class Bus extends Vehicle {
    public Bus(Road road) {
        super(road);
    }

    @Override
    void drive() {
        System.out.print("开公交车");
        road.driveOnRoad();
    }
}


package test9;

public class Car extends Vehicle{
    public Car(Road road) {
        super(road);
    }

    @Override
    void drive() {
        System.out.print("开车");
        road.driveOnRoad();
    }
}
package test9;

// 路抽象类
public interface Road {
     void driveOnRoad();
}

package test9;

// 车辆抽象类
abstract class Vehicle {
    protected Road road;

    public Vehicle(Road road) {
        this.road = road;
    }

    abstract void drive();
}
package test9;

public class ConcreteAsphaltRoad implements Road {
    @Override
    public void driveOnRoad() {
        System.out.println("在沥青路上");
    }
}


package test9;

// 具体路类
public class ConcreteCementRoad implements Road {
    @Override
    public void driveOnRoad() {
        System.out.println("在水泥路上");
    }
}
package test9;

public class Main {
    public static void main(String[] args) {
        Road cementRoad = new ConcreteCementRoad();
        Road asphaltRoad = new ConcreteAsphaltRoad();

        Vehicle carOnCement = new Car(cementRoad);
        Vehicle busOnCement = new Bus(cementRoad);
        Vehicle busOnAsphalt = new Bus(asphaltRoad);

        carOnCement.drive(); // 开车在水泥路上
        busOnAsphalt.drive(); // 开公交车在沥青路上
        busOnCement.drive(); //开公交车在水泥路上
    }
}

 

posted @ 2023-11-06 22:10  一个小虎牙  阅读(35)  评论(0编辑  收藏  举报