十五、桥接模式

1、什么是桥接模式

  • Bridge 模式又叫做桥接模式,是构造型的设计模式之一。Bridge模式基于类的最小设计原则,通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象(abstraction)与行为实现(implementation)分离开来,从而可以保持各部分的独立性以及应对它们的功能扩展。

2、桥接模式的结构

在这里插入图片描述

3、桥接模式的角色和职责

  • Client
    • Bridge模式的使用者
  • Abstraction
    • 抽象类接口(接口或抽象类)
    • 维护对行为实现(Implementor)的引用
  • Refined Abstraction
    • Abstraction子类
  • Implementor
    • 行为实现类接口 (Abstraction接口定义了基于Implementor接口的更高层次的操作)
  • ConcreteImplementor
    • Implementor子类

4、代码实现

package com.example.demo03;

public interface Engine {

	public void installEngine();
}
package com.example.demo03;

public class Engine2000 implements Engine{

	@Override
	public void installEngine() {
		System.out.println("安装2000CC发动机");
	}

}
package com.example.demo03;

public class Engine2200 implements Engine{

	@Override
	public void installEngine() {
		System.out.println("安装2200CC发动机");
	}

}
package com.example.demo03;

public class Bus extends Car {

	public Bus(Engine engine) {
		super(engine);
	}

	@Override
	public void installEngine() {
		System.out.print("Bus:");
		this.getEngine().installEngine();
	}

}
package com.example.demo03;

public abstract class Car {

	private Engine engine;
	
	public Car(Engine engine){
		this.engine = engine;
	}
	
	
	public Engine getEngine() {
		return engine;
	}


	public void setEngine(Engine engine) {
		this.engine = engine;
	}


	public abstract void installEngine();
}
package com.example.demo03;

public class Jeep extends Car {

	public Jeep(Engine engine) {
		super(engine);
	}

	@Override
	public void installEngine() {
		System.out.print("Jeep:");
		this.getEngine().installEngine();
	}

}
package com.example.demo03;

import org.junit.Test;

public class MainClass {

	@Test
	public void test01(){
		Engine engine2000 = new Engine2000();
		Engine engine2200 = new Engine2200();
		
		Car bus1 = new Bus(engine2000);
		bus1.installEngine();

		Car bus2 = new Bus(engine2200);
		bus2.installEngine();
		
		Car jeep1 = new Jeep(engine2000);
		jeep1.installEngine();

		Car jeep2 = new Jeep(engine2200);
		jeep2.installEngine();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QQ719872578

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值