亲宝软件园·资讯

展开

Java桥接模式

爱学习的大鱼​​​​​​​ 人气:0

模式介绍

UML类图

类图说明:

桥接模式案例

背景介绍: 客户端通过桥接模式,根据手机功能和品牌进行相应功能的输出

手机品牌接口类及实现子类

public interface Brand {
    void open();
    void close();
    void call();
}
public class XiaoMi implements Brand {
    @Override
    public void open() {
        System.out.println("小米手机开机");
    }
    @Override
    public void close() {
        System.out.println("小米手机关机");
    }
    @Override
    public void call() {
        System.out.println("小米手机打电话");
    }
}
public class Vivo implements Brand{
    @Override
    public void open() {
        System.out.println("Vivo手机开机");
    }
    @Override
    public void close() {
        System.out.println("Vivo手机关机");
    }
    @Override
    public void call() {
        System.out.println("Vivo手机打电话");
    }
}

手机抽象类及实现子类

public abstract class Phone {
    private Brand brand;
    public Phone(Brand brand) {
        this.brand = brand;
    }
    protected void open(){
        this.brand.open();
    }
    protected void close(){
        this.brand.close();
    }
    protected void call() {
        this.brand.call();
    }
}
public class FoldedPhone extends Phone{

    public FoldedPhone(Brand brand) {
        super(brand);
    }
    @Override
    protected void open() {
        super.open();
        System.out.println("折叠样式手机");
    }
    @Override
    protected void close() {
        super.close();
        System.out.println("折叠样式手机");
    }
    @Override
    protected void call() {
        super.call();
        System.out.println("折叠样式手机");
    }
}
public class UpRightPhone extends Phone {
    public UpRightPhone(Brand brand) {
        super(brand);
    }
    @Override
    protected void open() {
        super.open();
        System.out.println("直立样式手机");
    }
    @Override
    protected void close() {
        super.close();
        System.out.println("直立样式手机");
    }
    @Override
    protected void call() {
        super.call();
        System.out.println("直立样式手机");
    }
}

客户端

public class Client {

    public static void main(String[] args) {
        Phone foldedPhone = new FoldedPhone(new XiaoMi());
        Phone upRightPhone = new UpRightPhone(new Vivo());
        foldedPhone.close();
        foldedPhone.open();
        foldedPhone.call();
        System.out.println("===============");
        upRightPhone.close();
        upRightPhone.open();
        upRightPhone.call();
    }
}

实现结果:

桥接模式的注意事项和细节

常见的应用场景

加载全部内容

相关教程
猜你喜欢
用户评论