Java设计模式——桥接模式
2021/9/7 17:06:23
本文主要是介绍Java设计模式——桥接模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
模式定义
桥接模式(Bridge Pattern)是将抽象部分和实现部分分离,使它们可以独立地改变,是一种对象结构型模式。
模式角色
桥接模式包含如下角色:
- Abstraction(抽象类)
- RefinedAbstraction(扩充抽象类)
- Implementor(实现类接口)
- ConcreteImplementor(具体实现类)
模式分析
桥接模式关键在于如何将抽象化与实现化解耦,使得两者可以独立改变。
抽象化:抽象就是忽略一些信息,将不同的实体当作同样的实体对待。在面向对象中将对象的共同性质抽取出来形成类的过程称之为抽象化的过程
实现化:针对抽象话给出的具体实现,就是实现化,抽象化与实现化是互逆的过程
解耦:解耦就是将抽象化和实现化直接的耦合解脱开,或者说将两者之间的强关联变成弱关联,将两个角色由继承改成关联关系(组合或者聚合)
模板代码:
public interface Implementor { public void operationImpl(); } public abstract class Abstraction { protected Implementor impl; public void setImpl(Implementor impl) { this.impl=impl; } public abstract void operation(); } public class RefinedAbstraction extends Abstraction { public void operation() { //代码 impl.operationImpl(); //代码 } }
模式例子
画出不同颜色的圆,DrawAPI 接口的实体类 RedCircle、GreenCircle。Shape 是一个抽象类,例子来自:http://www.runoob.com/design-pattern/bridge-pattern.html
创建桥接接口:
public interface DrawAPI { public void drawCircle(int radius, int x, int y); }
接口具体实现类:
public class RedCircle implements DrawAPI { @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: red, radius: " + radius +", x: " +x+", "+ y +"]"); } } public class GreenCircle implements DrawAPI { @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: green, radius: " + radius +", x: " +x+", "+ y +"]"); } }
抽象类关联方式实现接口:
public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } public abstract void draw(); }
具体类实现抽象类:
public class Circle extends Shape { private int x, y, radius; public Circle(int x, int y, int radius, DrawAPI drawAPI) { super(drawAPI); this.x = x; this.y = y; this.radius = radius; } public void draw() { drawAPI.drawCircle(radius,x,y); } } public class BridgePatternDemo { public static void main(String[] args) { Shape redCircle = new Circle(100,100, 10, new RedCircle()); Shape greenCircle = new Circle(100,100, 10, new GreenCircle()); redCircle.draw(); greenCircle.draw(); } }
模式应用
一些软件的跨平台设计有时候也是应用了桥接模式
JDBC的驱动程序,实现了将不同类型的数据库与Java程序的绑定
Java虚拟机实现了平台的无关性,Java虚拟机设计就是通过桥接模式
这篇关于Java设计模式——桥接模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求