Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3295869
  • 博文数量: 306
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2210
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(306)

文章存档

2022年(79)

2021年(155)

2020年(50)

2019年(22)

我的朋友

分类: Java

2020-05-13 17:23:01

原理

1将实现与抽象放在两个不同的类层次中,使两个层次可以独立改变,这是一种结构型设计模式

2桥接模式基于类最小设计原则,通过封装,聚合,继承等行为让不同的类层单不同的职责。主要特点是把抽象与行为实现分离开,从而保持各部分的独立性,以及对他们功能的扩展

代码

调用者

public class Client {

    public static void main(String[] args) {

        Phone phone1 = new FoldedPhone(new XiaoMi());

        phone1.open();

        phone1.close();

        phone1.call();

        Phone phone2 = new FoldedPhone(new Vivo());

        phone2.open();

        phone2.close();

        phone2.call();

 

        Phone phone3 = new UpRightPhone(new XiaoMi());

        phone3.open();

        phone3.close();

        phone3.call();

        Phone phone4 = new UpRightPhone(new Vivo());

        phone4.open();

        phone4.close();

        phone4.call();

    }

}

接口类

//接口

public interface Brand {

    void open();

 

    void close();

 

    void call();

}抽象类

public abstract class Phone {

 //组合品牌

    private Brand brand;

 

    public Phone(Brand brand) {

        super();

        this.brand = brand;

    } protected void open() {

        this.brand.open();

    }protected void close() {

        this.brand.close();

    }protected void call() {

        this.brand.call();

    }

}

抽象类子类A

public class FoldedPhone extends Phone {

 public FoldedPhone(Brand brand) {

        super(brand);

    } @Override

    public void open() {

        super.open();

        System.out.println("折叠式手机");

    } @Override

    public void close() {

        super.close();

        System.out.println("折叠式手机");

    }@Override

    public void call() {

        super.call();

        System.out.println("折叠式手机");

抽象类子类B

public class UpRightPhone extends Phone {

    public UpRightPhone(Brand brand) {

        super(brand);

    }@Override

    public void open() {

        super.open();

        System.out.println("直立式手机");

    } @Override

    public void close() {

        super.close();

        System.out.println("直立式手机");

    } @Override

    public void call() {

        super.call();

        System.out.println("直立式手机");

    }

具体实现类A

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手机打电话");

具体实现类B

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("小米手机打电话");

    }

}

阅读(1085) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~