我有一个接口,其2个实现说:
public interface ObjectProcessor { public void process(ListobjectNames); } public CarImpl implements ObjectProcessor { @override public void process(List carNames){ //car logic } } public VanImpl implements ObjectProcessor { @override public void process(List vanNames){ //van logic } }
现在使用此界面的调用者看起来像:
public void caller(VehicleType vehicleType, ListvehicleNames ) { ObjectProcessor processor = null ; if (VehicleType == VehicleType.CAR) { processor = new CarImpl(); processor.process(vehicleNames); } }
VehicleType是ENUM这很好用.但无论如何我可以动态调用接口而无需
添加if语句.将来,如果我支持其他车辆,我需要添加一个if语句以及该接口的新实现.我怎么能避免这个?
像这样覆盖枚举中的抽象工厂方法.
public enum VehicleType { Car { @Override public ObjectProcessor createImpl() { return new CarImpl(); } }, Van { @Override public ObjectProcessor createImpl() { return new VanImpl(); } }; public abstract ObjectProcessor createImpl(); } public void caller(VehicleType vehicleType, ListvehicleNames ) { ObjectProcessor processor = vehicleType.createImpl(); processor.process(vehicleNames); }
VechicleType将枚举与工厂结合在一起.
或者你可以像这样在枚举中记录所有逻辑.
public enum VehicleType { Car { @Override public ObjectProcessor createImpl() { return new ObjectProcessor() { @Override public void process(ListobjectNames) { // car logic } }; } }, Van { @Override public ObjectProcessor createImpl() { return new ObjectProcessor() { @Override public void process(List objectNames) { // van logic } }; } }; public abstract ObjectProcessor createImpl(); }
在这种情况下,您不再需要实现类(CarImpl,VanImpl,...).