【桥接模式的示例】根据不同的告警规则,触发不同类型的告警。告警支持多种通知渠道,包括:邮件、短信、微信、自动语音电话。通知的紧急程度有多种类型,包括:SEVERE(严重)、URGENCY(紧急)、NORMAL(普通)、TRIVIAL(无关紧要)。不同的紧急程度对应不同的通知渠道。比如,SERVE(严重)级别的消息会通过“自动语音电话”告知相关人员。
import java.util.List;
public enum NotificationEmergencyLevel {
SEVERE, URGENCY, NORMAL, TRIVIAL
}class Notification{
private List emailAddresses;
private List telephones;
private List wechatIds;
public Notification() {}public void setEmailAddress(List emailAddress) {
this.emailAddresses = emailAddress;
}
public void setTelephones(List telephones) {
this.telephones = telephones;
}
public void setWechatIds(List wechatIds) {
this.wechatIds = wechatIds;
}public void notify(NotificationEmergencyLevel level,String message){
if (level.equals(NotificationEmergencyLevel.SEVERE)){
//电话通知
}else if (level.equals(NotificationEmergencyLevel.URGENCY)){
//微信
}elseif (level.equals(NotificationEmergencyLevel.NORMAL)){
//邮件
}else if (level.equals(NotificationEmergencyLevel.TRIVIAL)){
//邮件
}
}
}//客户端如何使用
class ErrorAlertHandler extends AlertHandler {
public ErrorAlertHandler(AlertRule rule, Notification notification){
super(rule, notification);
}
@Override
public void check(ApiStatInfo apiStatInfo){
if (apiStatInfo.getErrorCount() > rule.getMatchedRule(apiStatInfo.getApi()).getMaxErrorCount()){
notification.notify(NotificationEmergencyLevel.SEVERE, "...");
}
}
}/*Notification类有一处明显的问题就是使用的if太多了,另外if里的是发送报警逻辑会很复杂,
我们将不同渠道的发送逻辑剥离出来,形成独立的消息发送类(MsgSender 相关类)。
其中,Notification 类相当于抽象,MsgSender 类相当于实现,两者可以独立开发,通过组合关系(也就是桥梁)任意组合在一起*/---------------改进版本-------------interface MsgSender{
void send(String message);
}class TelephoneMsgSender implements MsgSender{
private List telephones;
public TelephoneMsgSender(List telephones) {
this.telephones = telephones;
}
@Override
public void send(String message) {
//...
}
}
class EmailMsgSender implements MsgSender {
// 与TelephoneMsgSender代码结构类似,所以省略...
}
class WechatMsgSender implements MsgSender {
// 与TelephoneMsgSender代码结构类似,所以省略...
}abstract class Notification {
protected MsgSender msgSender;
public Notification(MsgSender msgSender) {
this.msgSender = msgSender;
}public abstract void notify(String message);
}class SevereNotification extends Notification {
public SevereNotification(MsgSender msgSender){
super(msgSender);
}@Override
public void notify(String message) {
msgSender.send(message);
}
}class UrgencyNotification extends Notification {// 与SevereNotification代码结构类似,所以省略...}class NormalNotification extends Notification { // 与SevereNotification代码结构类似,所以省略...}class TrivialNotification extends Notification { // 与SevereNotification代码结构类似,所以省略...}
推荐阅读
- 设计模式【15】--从审批流中学习责任链模式
- 设计模式【14】-- 从智能音箱中学习命令模式
- 设计模式——工厂方法模式(创建型模式)
- Java中的桥接模式
- Java中的适配器模式
- Java中的原型模式
- Java中的工厂模式
- Java中的抽象工厂模式
- Java中的单例模式
- Java设计模式|Java设计模式-单例模式