Python 官方文档:入门教程 => 点击学习
目录定义案例需求方案一方案二对比分析总结定义 桥梁模式是对象的结构模式。又称为柄体(Handle and Body)模式或接口(Interface)模式。桥梁模式的用意是&ldquo
桥梁模式是对象的结构模式。又称为柄体(Handle and Body)模式或接口(Interface)模式。桥梁模式的用意是“将抽象化(Abstraction)与实现化(Implementation)脱耦,使得二者可以独立地变化”。
通过企业微信和qq的方式给员工发送消息
定义发送消息的接口
public interface AbstractSendMsgService {
// 发送消息
public void sendMsg();
}
定义普通消息接口
public interface CommonMsg extends AbstractSendMsgService{
}
定义微信消息实现类
public class WxMsgServiceImpl implements CommonMsg{
@Override
public void sendMsg() {
System.out.println("老板使用微信给你发了消息,快去接收吧");
}
}
定义QQ消息实现类
public class QqMsgServiceImpl implements CommonMsg{
@Override
public void sendMsg() {
System.out.println("老板使用QQ给你发了消息,快去接收吧");
}
}
定义测试类
public class Test {
public static void main(String[] args) {
new WxMsgServiceImpl().sendMsg();
new QqMsgServiceImpl().sendMsg();
}
}
测试结果
定义发送消息抽象接口
public abstract class NewAbstractSendMsgService {
protected SendMsgImplementor sendMsgImplementor;
public NewAbstractSendMsgService(SendMsgImplementor sendMsgImplementor){
this.sendMsgImplementor = sendMsgImplementor;
}
// 微信
public void sendMsg(){
this.sendMsgImplementor.sendMsg();
}
}
定义发送消息实现类
public class NewSendMsgServiceImpl extends NewAbstractSendMsgService{
public NewSendMsgServiceImpl(SendMsgImplementor sendMsgImplementor) {
super(sendMsgImplementor);
}
@Override
public void sendMsg() {
super.sendMsg();
}
}
定义发送消息统一接口
public interface SendMsgImplementor {
void sendMsg();
}
定义微信发送消息实现类
public class WxImplementor implements SendMsgImplementor{
@Override
public void sendMsg() {
System.out.println("老板使用微信给你发了消息,快去接收吧");
}
}
定义QQ发送消息实现类
public class QqImplementor implements SendMsgImplementor{
@Override
public void sendMsg() {
System.out.println("老板使用QQ给你发了消息,快去接收吧");
}
}
定义测试类
public class TestNew {
public static void main(String[] args) {
NewSendMsgServiceImpl newSendMsgService = new NewSendMsgServiceImpl(new QqImplementor());
newSendMsgService.sendMsg();
NewSendMsgServiceImpl newSendMsgService2 = new NewSendMsgServiceImpl(new WxImplementor());
newSendMsgService2.sendMsg();
}
}
测试结果
方案一,即一般实现方式,微信和QQ两种发送消息的方式需要同时去实现CommonMsg和AbstractSendMsgService两个接口中的方法,耦合性较高;另外比如新增紧急消息的发送或者新增短信的方式发送消息的需求,改动较多,扩展性较差。
方案二,为桥接模式实现方式,在消息类的构造方法中传入接口SendMsgImplementor,从而使发送消息的抽象和具体实现进行了分离,实现了解耦;后期新增紧急消息的发送或者新增短信的方式发送消息的需求,也只需要新增紧急消息类和短信发送类即可,和QQ,微信等发送消息互不影响,扩展方便,符合开闭原则,复用原则。
桥梁模式分离了抽象部分和实现部分,从而极大地提供了系统的灵活性。让抽象部分和实现部分独立出来,分别定义接口,这有助于对系统进行分层,从而产生更好的结构化的系统。
桥梁模式使得抽象部分和实现部分可以分别独立地扩展,而不会相互影响,从而大大提高了系统的可扩展性。
到此这篇关于Java设计模式之桥接模式的示例详解的文章就介绍到这了,更多相关Java桥接模式内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java设计模式之桥接模式的示例详解
本文链接: https://www.lsjlt.com/news/139904.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0