接口隔离原则:
不应该强迫客户程序依赖并未使用的方法。
该原则是用来处理"胖"接口所存在的缺点。如果类的接口不是内聚的,就表示该类具有"胖"接口。
示例:
考虑一个安全系统。在这个系统中,有一些Door对象,可以被加锁和解锁,并且Door对象知道自己是开着还是关着,如下:
package com.pptb.design.patterns.isp;
public interface Door {
void lock();
void unLock();
void isDoorOpen();
}
现在,考虑一个这样的实现,TimedDoor,如果门开着的时间过长,它就会发出警报声。为了做到这一点,TimedDoor需要和另外一个名为Timer的对象交互,如下:
public class Timer {
public void register(int timeOut,TimerClient client){
//TODO:
}
}
public interface TimerClient {
void timeOut();
}
如果让Door继承TimerClient,那TimedDoor就可以把自己注册到Timer接收TimeOut消息,但是这样就导致了Door类依赖于TimerClient了,然而并不是所有的Door都需要定时的功能,所以这种让Door继承TimerClient的设计违反了LSP原则。
所以我们使用委托来分离接口:
public interface Door {
void lock();
void unLock();
void isDoorOpen();
}
public class Timer {
public void register(int timeOut,TimerClient client){
//TODO:
}
}
public interface TimedDoor extends Door {
void doorTimeOut();
}
public interface TimerClient {
void timeOut();
}
public class DoorTimerAdapter implements TimerClient {
private TimedDoor timedDoor;
public DoorTimerAdapter(TimedDoor theDoor) {
this.timedDoor = theDoor;
}
@Override
public void timeOut() {
this.timedDoor.doorTimeOut();
}
}
如上使用DoorTimerAdapter类来分离接口。
网友评论