桥接模式
Bridge模式基于类的最小设计原则,通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象(abstraction)与行为实现(implementation)分离开来,从而可以保持各部分的独立性以及应对它们的功能扩展。
像我们常用的JDBC桥DriverManager一样,JDBC进行连接数据库的时候,在各个数据库之间进行切换,基本不需要动太多的代码,甚至丝毫不用动,原因就是JDBC提供统一接口,每个数据库提供各自的实现,用一个叫做数据库驱动的程序来桥接就行了。
下面还是以票务系统为例:
票务系统接口定义
1 public interface TicketsSystem {
2 void buyTicket();
3 }
2 void buyTicket();
3 }
接下来是两个实现类
汽车票
1 public class BusTickets implements TicketsSystem{
2
3 public void buyTicket() {
4 System.out.println("buy a busTickets!");
5 }
6
7 }
2
3 public void buyTicket() {
4 System.out.println("buy a busTickets!");
5 }
6
7 }
火车票
1 public class TrainTickets implements TicketsSystem{
2
3 public void buyTicket() {
4 System.out.println("buy a trainTickets!");
5 }
6
7 }
2
3 public void buyTicket() {
4 System.out.println("buy a trainTickets!");
5 }
6
7 }
桥的抽象定义
1 public abstract class TicketsBridge implements TicketsSystem {
2 private TicketsSystem system;
3
4 public TicketsSystem getSystem() {
5 return system;
6 }
7
8 public void setSystem(TicketsSystem system) {
9 this.system = system;
10 }
11
12 }
2 private TicketsSystem system;
3
4 public TicketsSystem getSystem() {
5 return system;
6 }
7
8 public void setSystem(TicketsSystem system) {
9 this.system = system;
10 }
11
12 }
桥的实例
1 public class TicketsManager extends TicketsBridge{
2
3 public TicketsManager(TicketsSystem system){
4 setSystem(system);
5 }
6
7 @Override
8 public void buyTicket() {
9 getSystem().buyTicket();
10
11 }
12
13 }
2
3 public TicketsManager(TicketsSystem system){
4 setSystem(system);
5 }
6
7 @Override
8 public void buyTicket() {
9 getSystem().buyTicket();
10
11 }
12
13 }
测试:
1 public class BridgeDemoTest {
2 public static void main(String[] args) {
3 TicketsManager manager;
4 BusTickets bus = new BusTickets();
5 manager = new TicketsManager(bus);
6 manager.buyTicket();
7
8 TrainTickets train = new TrainTickets();
9 manager = new TicketsManager(train);
10 manager.buyTicket();
11 }
12 }
2 public static void main(String[] args) {
3 TicketsManager manager;
4 BusTickets bus = new BusTickets();
5 manager = new TicketsManager(bus);
6 manager.buyTicket();
7
8 TrainTickets train = new TrainTickets();
9 manager = new TicketsManager(train);
10 manager.buyTicket();
11 }
12 }