一个关于visitor模式的问题,大家帮忙看看是为什么。
被访问体系是IChargeEvent(计费事件),有很多子类,而且会继续扩展。
访问者体系是IChargeWay(计费方式),也有很多子类,也会继续扩展。而且每个具体的计费方式并不是支持所有的计费事件。
这种情况下用传统的访问者模式不是很好,因此我没有在IChargeWay中对每个计费事件都定义访问方法,而是定义了对IChargeEvent
的访问方法。在子类中实现对IChargeEvent的访问方法,并且对每个IChargeEvent子类定义一个重载方法。如下:
public interface IChargeWay
{
ChargeResult doCharge(IChargeEvent event);
}
public class SMChargeWay implements IChargeWay
{
public ChargeResult doCharge(IChargeEvent event)
{
// not supported IChargeEvent subclass will come to this overload method.
System.out.println("no supported charge event.");
}
public ChargeResult doCharge(DownToneEvent event)
{
// DownToneEvent charge
System.out.println("DownToneEvent charge process.");
}
... more overload method for IChargeEvent subclass
}
<p class="indent">
|
然后在IChargeEvent体系有一个方法接受IChargeWay对象。
public interface IChargeEvent
{
ChargeResult chargeBy(IChargeWay way);
}
public class DownToneEvent implements IChargeEvent
{
public ChargeResult chargeBy(IChargeWay way)
{
return way.doCharge(this);
}
}
public class CopyToneEvent implements IChargeEvent
{
public ChargeResult chargeBy(IChargeWay way)
{
return way.doCharge(this);
}
}
<p class="indent">
|
这里是测试程序:
public class Test
{
public static void main(String[] args)
{
IChargeEvent dtEvent = new DownToneEvent();
IChargeWay smWay = new SMChargeWay();
// I expect the following method printing "DownToneEvent charge process."
// But actually, it prints "no supported charge event."
dtEvent.chargeBy(smWay);
}
}
<p class="indent">
|
为什么没有走到对于该事件的重载方法内,难道继承来的方法就不能被重载了么?恳求大侠指点迷津!!!