当前位置: 首页 > news >正文

六、桥接模式

桥接模式(Bridge Pattern)是一种结构型设计模式,旨在将抽象与实现分离,使得两者可以独立变化。通过使用桥接模式,可以避免在多个维度上进行继承,降低代码的复杂度,从而提高系统的可扩展性。

组成部分

  1. 抽象类(Abstraction): 定义高层的抽象接口,并持有对实现的引用。
  2. 扩展抽象类(RefinedAbstraction): 继承自抽象类,提供具体的扩展实现。
  3. 实现接口(Implementor): 定义实现部分的接口。
  4. 具体实现类(ConcreteImplementor): 实现实现接口的具体类。

JAVA: 

// 1、定义一个图像接口
public interface Graph {//画图方法 参数:半径 长 宽public void drawGraph(int radius, int x, int y);
}
// 红色图形
public class RedGraph implements Graph{@Overridepublic void drawGraph(int radius, int x, int y) {System.out.println("红色");}
}
// 创建一个形状
public abstract class Shape {public Graph graph;public Shape(Graph graph){this.graph = graph;}public abstract void draw();
}
// 圆形
public class Circle extends Shape{private int radius;private int x;private int y;public Circle(int radius, int x, int y, Graph graph) {super(graph);this.radius = radius;this.x = x;this.y = y;}@Overridepublic void draw() {System.out.println("圆形");graph.drawGraph(radius, x, y);}
}
@Test(description = "桥接模式")public void bridgePatternTest(){//创建圆形Shape shape = new Circle(10, 100, 100, new RedGraph());shape.draw();}

 GO:

package bridgeimport "fmt"// 桥接模式// IMsgSender 消息发送接口
type IMsgSender interface {// Send 发送动作函数Send(msg string) error
}// EmailMsgSender发送邮件
// 可能还有 电话、短信等各种实现
type IMsgReceiver struct {emails []string
}func (I IMsgReceiver) Send(msg string) error {// 这里去发送消息fmt.Println(msg, "消息发送成功")return nil
}func NewEmailMsgSender(emails []string) *IMsgReceiver {return &IMsgReceiver{emails: emails}
}// INotification 通知接口
type INotification interface {// Notify 通报函数Notify(msg string) error
}// ErrorNotification 错误通知
// 后面可能还有 warning 各种级别
type ErrorNotification struct {sender IMsgSender
}// Notify 发送通知
func (e ErrorNotification) Notify(msg string) error {return e.sender.Send(msg)
}func NewErrorNotification(sender IMsgSender) *ErrorNotification {return &ErrorNotification{sender: sender}
}
func TestBridge(t *testing.T) {sender := NewEmailMsgSender([]string{"test@test.com"})n := NewErrorNotification(sender)err := n.Notify("test msg")assert.Nil(t, err)
}

http://www.lryc.cn/news/431427.html

相关文章:

  • Vue eslint 语法检测问题
  • QT Creater实现国庆节主题项目【0基础完成版】
  • Qt 加载 WPS 时提示要登录
  • vue3的el-tree的default-checked-keys无法勾选的问题解决
  • class 5: vue.js 3 v-model和表单输入
  • 了解一下HTTP 与 HTTPS 的区别
  • Opencv中的直方图(1)计算反向投影直方图函数calcBackProject()的使用
  • VUE3项目的几种创建方式
  • VBA进行excel坐标转换
  • 使用pytorch深度学习框架搭建神经网络
  • Hive数据库与表操作全指南
  • UniaApp引入Iconfont
  • 面试题:软件测试缺陷产生的原因有哪些?
  • RabbitMQ 04 集群
  • axure9勾选多个删除,弹框显示多个中继器编号
  • Git 使用指南 --- 版本管理
  • C#进阶-ASP.NET实现可以缩放和旋转的图片预览页
  • 【小程序 - 大智慧】深入微信小程序的核心原理
  • Qt 去掉QDialog对话框的问号
  • 负载均衡 Ribbon 与 Fegin 远程调用原理
  • c/c++:CMakeLists.txt中添加编译/连接选项使用内存错误检测工具Address Sanitizer(ASan)
  • armbian cups 远程打印机 1022
  • three.js使用3DTilesRendererJS加载3d tiles数据
  • 坐牢第三十五天(c++)
  • Conda离线部署django
  • 1. Fabric.js安装使用
  • Excel中.xls和.xlsx文件格式的区别,及C++操作Excel文件
  • php实用命令
  • TypeError:未绑定方法
  • Java虚拟机(JVM)的架构和工作原理,字节码执行流程