Sunday, May 10, 2015

Implement State Pattern Using Enum in Java.

State Pattern is a common design pattern. Let's see how to implement one in Java code using enum.

First we define an Interface: LunchFace with one method declaration: getLunch();
 public interface LunchFace {  
      void getLunch();  
 }  



Then we create an enum to implement the LunchFace interface.
public enum Weekday implements LunchFace{
    MONDAY
    , TUESDAY
    , WEDNESDAY{
        @Override
        public void getLunch() {
            System.out.println("Lunch for " + this.name());
        }
    };

    
    
    @Override
    public void getLunch() {
        System.out.println("lunch for today");
    }

}



Notice here we have the enum implement the LunchFace as a default implementation, we can also have each enum item to have its own implementation by override the getLunch() method.

Now we can test run our code
public class Main {

    public static void main(String[] args) {
        Weekday someday = Weekday.WEDNESDAY;
        someday.getLunch();
        
        someday = Weekday.TUESDAY;
        someday.getLunch();
    
    }

}


And the output should be:
Lunch for WEDNESDAY
lunch for today






No comments:

Post a Comment