桥接模式: 将实现与抽象放在两个不同的类层次中,使两个层次可以独立改变。
public abstract class Phone {
private Brand brand;
public Phone(Brand brand){
this.brand = brand;
}
public void open() {
this.brand.open();
}
public void close() {
this.brand.close();
}
public void call() {
this.brand.call();
}
}
public class FoldedPhone extends Phone{
public FoldedPhone(Brand brand) {
super(brand);
}
public void open() {
super.open();
System.out.println("折叠样式");
}
public void close() {
super.close();
System.out.println("折叠样式");
}
public void call() {
super.call();
System.out.println("折叠样式");
}
}
public interface Brand {
void open();
void close();
void call();
}
public class HuaWei 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 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 Client {
public static void main(String[] args){
XiaoMi x = new XiaoMi();
FoldedPhone p = new FoldedPhone(x);
p.open();
p.call();
p.close();
}
}
桥接模式在jdbc中使用
jdbc的Driver接口, 如果从桥接模式来看,Driver就是一个接口,下面可以有MySQL的Driver, Oracle的Driver, 这些就可以当做实现接口类。