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