public class MethodBVisitor implements Visitor
public void visit(Visitable visitable)
{
ConcreteClass c=(ConcreteClass)visitable;
methodB(c);
}
private void methodB(ConcreteClass c)
{
//call public method in ConcreteClass, here is the new logic!
}
client的调用方式改为
ConcreteClass c=new ConcreteClass ();
c.methodA();
Visitor v=new MethodBVisitor();
c.accept(v);//methodB implemented in MethodBVisitor instead of in ConcreteClass
ConcreteClass c=new ConcreteClass ();
c.methodA();
List<Visitor> vList=XMLConfigFactory.load(VISITOR_CLASS_LIST); //create object base on reflection, similiar to Spring IoC
for(Visitor v:vList) c.accept(v);
理想的情况是
private void methodB(ConcreteClass c)
{
//call public method in ConcreteClass, here is the new logic!
c.method1();
c.method2();
... ...
c.methodN();
}
目前如果有人想做到这个极致化,确实很傻,但是,The OpenClosedPrinciple (OCP): "A reusable class should be open for extension, but closed for modification." (我已经记不清这是第几次引用这个了),能够在OO的领域提出这样的一个原则,说明这个极致化,是符合OO精神的,代表着更高质量的代码。无论是修改还是增加新功能,只增加新的类,不修改旧的类,旧的类一旦单元测试通过就永久冻结,新增加的类测试通过后,也冻结,这样增量的开发模式,使得推进的步伐更坚定,软件的质量更可靠。当然,极致化的前提是,架构的水平足够高,设计的水平足够高,需求分析的水平足够高。