java 桥接模式

时间:2022-09-19 10:53:51

桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。

1)适配器:改变已有的两个接口,让他们相容。

2)桥接模式:分离抽象化和实现,使两者的接口可以不同,目的是分离。

/**
* @author liusongwei
* @Title: Car
* @ProjectName demohystrix
* @Description: 定义一个交通工具的接口
* @date 2018/12/2815:58
*/
public interface Traffic {
void byontake(String name);
}
/**
* @author liusongwei
* @Title: Plane
* @ProjectName demohystrix
* @Description: 交通工具之一飞机
* @date 2018/12/2816:02
*/
public class Plane implements Traffic {
@Override
public void byontake(String name) {
System.out.println(name + "乘坐飞机去少林寺");
}
}
/**
* @author liusongwei
* @Title: Train
* @ProjectName demohystrix
* @Description: 交通工具之一火车
* @date 2018/12/2816:00
*/
public class Train implements Traffic {
@Override
public void byontake(String name) {
System.out.println(name + "乘坐火车去少林寺");
}
}
/**
* @author liusongwei
* @Title: Whois
* @ProjectName demohystrix
* @Description: 定义一个抽象类谁乘坐交通工具
* @date 2018/12/2816:03
*/
public abstract class Whois {
private Traffic traffic; public Whois(Traffic traffic){
this.traffic = traffic;
} public void WhereGoTo(String name){
traffic.byontake(name);
}
}
/**
* @author liusongwei
* @Title: Man
* @ProjectName demohystrix
* @Description: 人类
* @date 2018/12/2816:06
*/
public class Man extends Whois {
public Man(Traffic traffic) {
super(traffic);
}
}
/**
* @author liusongwei
* @Title: Demo
* @ProjectName demohystrix
* @Description: TODO
* @date 2018/12/2816:07
*/
public class Demo {
public static void main(String[] args){
Whois whois = new Man(new Train());
whois.WhereGoTo("张三"); Whois whois2 = new Man(new Plane());
whois2.WhereGoTo("李四"); }
}