桥接模式:
对于有两个变化维度的系统,例如电脑的种类与品牌,桥接模式将继承关系转换为关联关系,从而降低了类与类之间的耦合,减少了代码编写量, 方便了后期扩展。
首先品牌属性,先定义一个接口:
public interface Brand {
void statement();
}
定义两个实现类(代表两个品牌):
class Dell implements Brand{
@Override
public void statement() {
System.out.println("Dell品牌");
}
}
class Lenovo implements Brand{
@Override
public void statement() {
System.out.println("Lenovo品牌");
}
}
然后是电脑类,电脑类的作为桥梁,内部有品牌类作为属性
public class Computer {//Computer类作为桥梁,组合了品牌类
private Brand brand;//内置品牌类属性
public Computer(Brand brand) {
this.brand = brand;
}
public void statement(){
brand.statement();
}
}
两个电脑类子类继承电脑类
class Laptop extends Computer{
public Laptop(Brand brand) {
super(brand);
}
public void statement(){
super.statement();
System.out.println("笔记本");
}
}
class Desktop extends Computer{
public Desktop(Brand brand) {
super(brand);
}
public void statement(){
super.statement();
System.out.println("台式机");
}
}
客户端测试实现桥接模式:
public class client {
public static void main(String[] args) {
Brand b=new Lenovo();
Computer c=new Desktop(b);
c.statement();
}
}