访问者模式(双重分派)在其本身就是非常有用的模式,但它经常被指责破坏接口,如果任何新成员被添加到继承层次结构中,这是一个有效的观点。
但是,在Java 8引入默认方法之后,现在我们可以在接口中定义默认实现,客户端接口将不会被破坏,客户端可以根据需要优雅地采用更改后的接口。
interface Visitor{
public void visit(Type1 type);
public void visit(Type2 type);
//added after the first version of visitor is released
default public void visit(NewType type){
//some default implementation
}
}
现在使用默认方法,如果未来引入新类型NewType
,不会再破坏客户端代码。
这样改进后的Visitor模式更易于接受和使用吗?