Clean Java

There is always a bigger game

Enum as state machine.

with one comment

Enum can be effectively used to encapsulate behavior. Here is a simple example where Enum is used to encapsulate a simple positive workflow.


package org.sanju.worflow;

public class Entity {
	
	private enum State{
		
		OPEN{
			void prceed(Entity entity) {
				entity.state = PENDING_APPROVAL;
			}
			
		},
		PENDING_APPROVAL{
			void prceed(Entity entity) {
				entity.state = APPROVED;
			}
			
		},
		APPROVED{
			void prceed(Entity entity) {
				entity.state = CLOSED;
				sendNotifcation(entity);
			}
			
		},
		CLOSED{
			void prceed(Entity entity) {
				throw new RuntimeException("Entity already closed");
			}
		};
		
		abstract void prceed(Entity entity);
	}
	
	private State state = State.OPEN;

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}
	
	public void proceed(){
		this.state.prceed(this);
	}
	
	private static void sendNotifcation(Entity entity){}
	
}

package org.sanju.worflow;

public class EntityClient {
	
	public static void main(String[] args) {
		
		Entity entity = new Entity();
		System.out.println(entity.getState());
		entity.proceed();
		System.out.println(entity.getState());
		entity.proceed();
		System.out.println(entity.getState());
		entity.proceed();
		System.out.println(entity.getState());
	}

}

/local/mnt/java org.sanju.EntityClient

OPEN
PENDING_APPROVAL
APPROVED
CLOSED

Advertisements

Written by cleanjava

February 25, 2012 at 9:30 pm

One Response

Subscribe to comments with RSS.

  1. setState won’t work in main since since State is private?

    Bob Edwards

    August 24, 2012 at 9:01 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: