I will try to explain my problem on cars. I have an AbstractCar, and the users (developers) of my library will create a lot of their ConcreteCars. This AbstractCar has a state, and this state is very important for the library to work properly! Only a car can manage its state (no drivers, etc.). The state changes in the start / stop methods at the beginning and at the end of methods. In addition, all vehicles must implement the Car interface.
public enum State{ STARTING, STARTED, STOPPING, STOPPED } public interface Car{ public void start(); public void stop(); public State getState(); }
I tried two options.
Option 1
public abstract class AbstractCar implements Car{ private State state; public void setState(State state){...} public State getState(){...} } public class ConcreteCar extends AbstractCar{ @Override public void start(){ setState(stateK); ... setState(stateN); } @Override public void stop(){ setState(stateR); ... setState(stateO); } }
In option 1, the library user will have to remember the state. If he does not, then there will be an error in the code.
Option 2
public abstract class AbstractCar implements Car{ private State state; protected void doOnStart(){ } protected void doOnStop(){ } public final void start(){ state=...; doOnStart(); state=...; } public final void stop(){ state=...; doOnStop(); state=...; } } public class ConcreteCar extends AbstractCar{ @Override protected void doOnStart(){ .... } @Override protected void doOnStop(){ ... } }
In option 2, the user cannot forget about the state, because he is already out of his control, but if I have many states and many methods in which they can be changed, this is not a good way.
Can anyone advise any template or technology how to solve such a problem?
source share