将类的抽象部分和它的实现部分分离开来,使它们可以独立地变化。
它是用聚合关系代替继承关系来实现的,从而降低了抽象和实现这两个可变维度的耦合度。
package com.strife.pattern.bridge;
/**
* 桥接模式
*
* @author mengzhenghao
* @date 2022/5/29
*/
public class Bridge {
public static void main(String[] args) {
Brand brand = new XiaoMi();
AbstractPhone phone = new FoldedPhone(brand);
phone.open();
phone.call();
phone.close();
brand = new Vivo();
phone = new FoldedPhone(brand);
phone.open();
phone.call();
phone.close();
phone = new UpRightPhone(brand);
phone.open();
phone.call();
phone.close();
}
}
interface Brand {
void open();
void close();
void call();
}
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("小米手机打电话");
}
}
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手机打电话");
}
}
/** 抽象手机类 */
abstract class AbstractPhone {
private Brand brand;
public AbstractPhone(Brand brand) {
this.brand = brand;
}
protected void open() {
this.brand.open();
}
protected void close() {
this.brand.close();
}
protected void call() {
this.brand.call();
}
}
/** 折叠式手机 */
class FoldedPhone extends AbstractPhone {
public FoldedPhone(Brand brand) {
super(brand);
}
protected void open() {
System.out.println("折叠手机");
super.open();
}
protected void close() {
System.out.println("折叠手机");
super.close();
}
protected void call() {
System.out.println("折叠手机");
super.call();
}
}
/** 直立式手机 */
class UpRightPhone extends AbstractPhone {
public UpRightPhone(Brand brand) {
super(brand);
}
protected void open() {
System.out.println("直立手机");
super.open();
}
protected void close() {
System.out.println("直立手机");
super.close();
}
protected void call() {
System.out.println("直立手机");
super.call();
}
}