设计模式:19、桥接模式

目录

0、定义

1、桥接模式的四种角色

2、桥接模式的UML类图

3、示例代码


0、定义

将抽象部门与实现部分分离,使它们都可以独立地变化。

1、桥接模式的四种角色

  • 抽象(Abstraction):一个抽象类,包含实现者(Implementor)声明的变量。
  • 实现者(Implementor):实现者 角色是一个接口(抽象类),该接口(抽象类)中的方法不一定与Abstraction 类中的方法一致。Implementor 接口(抽象类)负责定义基本操作,而Abstraction类负责定义基于这些操作的较高层次的操作。
  • 细化抽象(Refined Abstraction):细化抽象抽象 角色的一个子类,该子类在重写(覆盖)抽象 角色中的方法时,在给出一些必要的操作后,将委托Implementor类型对象调用相应的方法。
  • 具体实现者(Concrete Implementor):具体实现者 是实现(拓展)Implementor接口(抽象类)的类

2、桥接模式的UML类图

3、示例代码

实现者(对修改关闭)

java 复制代码
package xyz.jangle.design.bridge;

public interface Implementor {
	
	public void operationImp();

}

抽象(对修改关闭)

java 复制代码
package xyz.jangle.design.bridge;

public abstract class Abstraction {
	
	Implementor impl;
	
	public Abstraction(Implementor impl) {
		super();
		this.impl = impl;
	}

	public abstract void operation();

}

细化抽象(对拓展开放,可以实现多个细化抽象)

java 复制代码
package xyz.jangle.design.bridge;

public class RefinedAbstraction extends Abstraction {

	public RefinedAbstraction(Implementor impl) {
		super(impl);
	}

	@Override
	public void operation() {
		impl.operationImp();	//重要实现部分由Implementor的子类的operationImp()方法负责。
	}

}

具体实现者1(对拓展开放,可以新增具体实现者。)

java 复制代码
package xyz.jangle.design.bridge;

public class ConcreteImplementor1 implements Implementor {

	@Override
	public void operationImp() {
		System.out.println("to do something 1 ");
	}

}

具体实现者2

java 复制代码
package xyz.jangle.design.bridge;

public class ConcreteImplementor2 implements Implementor {

	@Override
	public void operationImp() {
		System.out.println("to do something 2 ");
	}

}

客户端(使用)

java 复制代码
package xyz.jangle.design.bridge;

public class AppMain19 {

	public static void main(String[] args) {
		
		ConcreteImplementor1 implementor1 = new ConcreteImplementor1();
		RefinedAbstraction refined = new RefinedAbstraction(implementor1);
		refined.operation();
		
		ConcreteImplementor2 implementor2 = new ConcreteImplementor2();
		RefinedAbstraction refined2 = new RefinedAbstraction(implementor2);
		refined2.operation();

	}

}

输出结果:

bash 复制代码
to do something 1 
to do something 2 
相关推荐
虫师c24 分钟前
分布式系统设计模式:从理论到实践
微服务·设计模式·系统架构·高可用·分布式系统
半旧夜夏26 分钟前
【设计模式】核心设计模式实战
java·spring boot·设计模式
ThisIsMirror2 小时前
设计模式简要介绍
设计模式
Lei活在当下8 小时前
【业务场景架构实战】7. 多代智能手表适配:Android APP 表盘编辑页的功能驱动设计
android·设计模式·架构
澄澈i10 小时前
设计模式学习[20]---桥接模式
c++·学习·设计模式·桥接模式
o0向阳而生0o11 小时前
106、23种设计模式之备忘录模式(15/23)
设计模式·备忘录模式
小猪佩奇TONY13 小时前
C++ 学习(3) ----设计模式
c++·学习·设计模式
zhulangfly1 天前
轻松理解智能体设计模式(1/6):提示链(Prompt Chaining)
设计模式·prompt chaining
da_vinci_x1 天前
2D角色动画进阶:Spine网格变形与序列帧特效的混合工作流
游戏·设计模式·设计师·photoshop·spine·游戏策划·游戏美术
代码萌新知2 天前
设计模式学习(五)装饰者模式、桥接模式、外观模式
java·学习·设计模式·桥接模式·装饰器模式·外观模式