桥接模式(接口模式)
- 类比于,二维平面的坐标,或多维坐标。"桥"将多个维度的接口(或实现)连接起来,构成新的产品。
Brand接口
package com.tiko.bridge;
//品牌接口
public interface Brand {
void info();
}
Apple品牌
package com.tiko.bridge;
//Apple品牌
public class Apple implements Brand {
@Override
public void info() {
System.out.print("Apple牌");
}
}
Lenovo品牌
package com.tiko.bridge;
public class Lenovo implements Brand {
@Override
public void info() {
System.out.print("联想牌");
}
}
抽象的电脑类(将Brand组合进该类)
package com.tiko.bridge;
//抽象的电脑类
public abstract class Computer {
//电脑自带品牌,所以将Brand组合为Computer的属性
//桥
private Brand brand;//protected 允许子类可以使用
public Computer(Brand brand) {
this.brand = brand;
}
public void info() {
brand.info();
}
}
Desktop类
package com.tiko.bridge;
public class Desktop extends Computer {
public Desktop(Brand brand) {
super(brand);
}
@Override
public void info() {
super.info();
System.out.println("desktop");
}
}
Laptop类
package com.tiko.bridge;
public class Laptop extends Computer {
public Laptop(Brand brand) {
super(brand);
}
@Override
public void info() {
super.info();
System.out.println("Laptop");
}
}
测试
package com.tiko.bridge;
import sun.security.krb5.internal.crypto.Des;
public class Test {
public static void main(String[] args) {
Computer laptop = new Laptop(new Apple());
laptop.info();
Computer desktop = new Desktop(new Lenovo());
desktop.info();
}
}
- 场景体现:
- Java的虚拟机实现平台的无关性
- JDBC
参考自狂神说