Java architectural class design for a real world scenario
这是我需要在Java中实现的问题:
汽车可以是汽油车或柴油车,并且混合动力车上装有汽油或柴油,但不能同时插入两者。另外,混合动力汽车具有完全依靠电力运行的能力,而根本不使用汽油或柴油,并且在运行时仅决定选择电力还是其他燃料源(适当时使用汽油或柴油)。
在这里,我需要考虑一个面向对象的概念,以一个示例为例,何时应调用汽油类型的以汽油模式运行的混合动力汽车方法,以及是否应调用其柴油-柴油级运行方法。
我是OOP的新手,我想出了以下设计我知道如果有人可以帮助我,那是错误的。
我尝试使用装饰器设计模式进行此操作,只是在上述情况下设计错误时才纠正我。
汽车接口
1 2 3 | public interface Car { public void running(); } |
汽油车类
1 2 3 4 5 6 7 | class PetrolCar implements Car{ public void running() { System.out.println("Running in Petrol"); } } |
柴油车类
1 2 3 4 5 6 7 | public class DieselCar implements Car{ public void running() { System.out.println("Running in Diesel"); } } |
抽象混合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public abstract class Hybrid implements Car{ Car car; public Hybrid(Car car) { this.car=car; } public void running(){ car.running(); } abstract void hybridRunning(); } |
实现混合类
1 2 3 4 5 6 7 8 9 10 11 12 | public class HybridCar extends Hybrid{ public HybridCar(Car car) { super(car); } @Override void hybridRunning() { System.out.println("Running in Hybrid Mood"); } } |
在运行时进行测试,用户可以选择汽车是混合汽油还是混合柴油,还是汽油还是柴油...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class App { public static void main(String[] args) { String neededType ="Petrol"; boolean hybrid = true; if (hybrid) { Hybrid hCar=null; if (neededType.equalsIgnoreCase("Petrol")) { hCar=(Hybrid)new HybridCar(new PetrolCar()); } else if (neededType.equalsIgnoreCase("Diesel")) { hCar=new HybridCar(new DieselCar()); } hCar.hybridRunning(); hCar.running(); } else { Car car=null; if (neededType.equalsIgnoreCase("Petrol")) { car=new PetrolCar(); } else if (neededType.equalsIgnoreCase("Diesel")) { car=new DieselCar(); } } } } |
这是正确的吗?关于OOP最佳做法是否存在任何问题
我将使用带有EnumSet燃料的单个类。
1 2 3 4 5 6 7 8 9 10 11 12 | public interface Car { static Car create(Fuel fuel, Fuel... others) { return new CarImpl(EnumSet.of(fuel, others)); } Set<Fuel> fuels(); void running(); enum Fuel { Petrol, Diesel, LPG, Hydrogren, Electric } } |
如果不使用Enum,则将使用不可变的类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public interface Car { static Car create(Fuel fuel, Fuel... others) { Set<Fuel> fuels = new HashSet<>(); fuels.add(fuel); Collections.addAll(fuels, others); return new CarImpl(fuels); } Set<Fuel> fuels(); void running(); void setMode (Fuel fuel) throws IllegalArgumentException; Fuel getMode (); class Fuel { private final String name; public Fuel(String name) { this.name = name; } public String name() { return name; } public String toString() { return name(); } public int hashCode() { return name().hashCode(); } public boolean equals(Object o) { return o instnaceof Fuel && ((Fuel) o).name().equals(name()); } } } |