开闭原则(OCP)

开闭原则(Open Closed Principle):软件实体(模块,类,方法等)应该对拓展开放,对修改关闭

software ebtities(modules,classes,function,etc.)should be open for extension,but closeed for modification

我的理解,大概就是,把一些容易变动的方法,抽象出来,多态来实现他,达到减少方法变动,举例

public class Alert {
  private AlertRule rule;
  private Notification notification;
<p>public Alert(AlertRule rule, Notification notification) {
this.rule = rule;
this.notification = notification;
}</p>
<p>public void check(String api, long requestCount, long errorCount, long durationOfSeconds) {
long tps = requestCount / durationOfSeconds;
if (tps > rule.getMatchedRule(api).getMaxTps()) {
notification.notify(NotificationEmergencyLevel.URGENCY, "...");
}
if (errorCount > rule.getMatchedRule(api).getMaxErrorCount()) {
notification.notify(NotificationEmergencyLevel.SEVERE, "...");
}
}
}

check方法中有两个条件判断是否需要通知,以后可能会有三个,四个更多的条件,参数的变动,当check比较复杂时,我们就得需要考虑使用开闭原则了,把check抽象,让不同的类实现check,统一调用,如

public class Alert {
private List<AlertHandler> alertHandlers = new ArrayList<>();</p>
<p>public void addAlertHandler(AlertHandler alertHandler) {
this.alertHandlers.add(alertHandler);
}</p>
<p>public void check(ApiStatInfo apiStatInfo) {
for (AlertHandler handler : alertHandlers) {
handler.check(apiStatInfo);
}
}
}</p>
<p>public class ApiStatInfo {//省略constructor/getter/setter方法
private String api;
private long requestCount;
private long errorCount;
private long durationOfSeconds;
}</p>
<p>public abstract class AlertHandler {
protected AlertRule rule;
protected Notification notification;
public AlertHandler(AlertRule rule, Notification notification) {
this.rule = rule;
this.notification = notification;
}
public abstract void check(ApiStatInfo apiStatInfo);
}</p>
<p>public class TpsAlertHandler extends AlertHandler {
public TpsAlertHandler(AlertRule rule, Notification notification) {
super(rule, notification);
}</p>
<p>@Override
public void check(ApiStatInfo apiStatInfo) {
long tps = apiStatInfo.getRequestCount()/ apiStatInfo.getDurationOfSeconds();
if (tps > rule.getMatchedRule(apiStatInfo.getApi()).getMaxTps()) {
notification.notify(NotificationEmergencyLevel.URGENCY, "...");
}
}
}</p>
<p>public class ErrorAlertHandler extends AlertHandler {
public ErrorAlertHandler(AlertRule rule, Notification notification){
super(rule, notification);
}</p>
<p>@Override
public void check(ApiStatInfo apiStatInfo) {
if (apiStatInfo.getErrorCount() > rule.getMatchedRule(apiStatInfo.getApi()).getMaxErrorCount()) {
notification.notify(NotificationEmergencyLevel.SEVERE, "...");
}
}
}