javaoopdesign-patternsstate-pattern

Knowing the state of an object using the state pattern


I am using the state pattern and I need to know in which state a given object is to print it. I thought about using an abstract method returning a string that each state would override with its own name, is it an acceptable solution?

public abstract class State{

    public abstract String getState();

}

class StateOne extends State{

    @Override
    public String getState(){ return "StateOne"; }

}

// And so on for each state...

Solution

  • It looks like you have is "is a" relationship, so it is okay to put abstract method getState() in abstract class:

    public abstract class State{
    
        public abstract String getState();
    
    }
    

    Abstract class should contain behaviour for all derived classes. getState() method is planned to use in all derived classes. In addition, getState() method has very high cohesion with State class. So this is a case when to use inheritance.

    Read more when to prefer inheritance or composition.