State Design Pattern Tutorial

State Design Pattern TutorialWelcome to my State Design Pattern Tutorial! I explain how the state pattern is used by using it to simulate an ATM machine.

I explain how you come to decide on the different states. I then show you how to design the interface that each state will use. We think about the methods that are needed for every class that implements the interface then.

All the steps are looked at from many directions and the code below will fill in the gaps.

If you like videos like this it helps to tell Google

Share if you think others may like it

Code From the Video

ATMSTATE.JAVA

public interface ATMState {
	
	// Different states expected
	// HasCard, NoCard, HasPin, NoCash
	
	void insertCard();
	
	void ejectCard();
	
	void insertPin(int pinEntered);
	
	void requestCash(int cashToWithdraw);
	
}

ATMMACHINE.JAVA

public class ATMMachine {
	
	ATMState hasCard;     
	ATMState noCard;
	ATMState hasCorrectPin;
	ATMState atmOutOfMoney;
	
	ATMState atmState;
	
	int cashInMachine = 2000;
	boolean correctPinEntered = false;
	
	public ATMMachine(){
		
		hasCard = new HasCard(this);
		noCard = new NoCard(this);
		hasCorrectPin = new HasPin(this);
		atmOutOfMoney = new NoCash(this);
		
		atmState = noCard;
		
		if(cashInMachine < 0){
			
			atmState = atmOutOfMoney;
			
		}
		
	}
	
	void setATMState(ATMState newATMState){
		
		atmState = newATMState;
		
	}
	
	public void setCashInMachine(int newCashInMachine){
		
		cashInMachine = newCashInMachine;
		
	}
	
	public void insertCard() {
		
		atmState.insertCard();
		
	}

	public void ejectCard() {
		
		atmState.ejectCard();
		
	}

	public void requestCash(int cashToWithdraw) {
		
		atmState.requestCash(cashToWithdraw);
		
	}

	public void insertPin(int pinEntered){
		
		atmState.insertPin(pinEntered);
		
	}
	
	public ATMState getYesCardState() { return hasCard; }
	public ATMState getNoCardState() { return noCard; }
	public ATMState getHasPin() { return hasCorrectPin; }
	public ATMState getNoCashState() { return atmOutOfMoney; }
	
}

HASCARD.JAVA

public class HasCard implements ATMState {
	
	ATMMachine atmMachine;
	
	public HasCard(ATMMachine newATMMachine){
		
		atmMachine = newATMMachine;
		
	}

	public void insertCard() {
		
		System.out.println("You can only insert one card at a time");
		
	}

	public void ejectCard() {
		
		System.out.println("Your card is ejected");
		atmMachine.setATMState(atmMachine.getNoCardState());
		
	}

	public void requestCash(int cashToWithdraw) {
		
		System.out.println("You have not entered your PIN");
		
		
	}

	public void insertPin(int pinEntered) {
		
		if(pinEntered == 1234){
			
			System.out.println("You entered the correct PIN");
			atmMachine.correctPinEntered = true;
			atmMachine.setATMState(atmMachine.getHasPin());
			
		} else {
			
			System.out.println("You entered the wrong PIN");
			atmMachine.correctPinEntered = false;
			System.out.println("Your card is ejected");
			atmMachine.setATMState(atmMachine.getNoCardState());
			
		}	
	}	
}

NOCARD.JAVA

public class NoCard implements ATMState {
	
	ATMMachine atmMachine;
	
	public NoCard(ATMMachine newATMMachine){
		
		atmMachine = newATMMachine;
		
	}

	public void insertCard() {
		
		System.out.println("Please enter your pin");
		atmMachine.setATMState(atmMachine.getYesCardState());
		
	}

	public void ejectCard() {
		
		System.out.println("You didn't enter a card");
		
	}

	public void requestCash(int cashToWithdraw) {
		
		System.out.println("You have not entered your card");
		
	}

	public void insertPin(int pinEntered) {
		
		System.out.println("You have not entered your card");
		
	}
}

HASPIN.JAVA

public class HasPin implements ATMState {
	
	ATMMachine atmMachine;
	
	public HasPin(ATMMachine newATMMachine){
		
		atmMachine = newATMMachine;
		
	}

	public void insertCard() {
		
		System.out.println("You already entered a card");
		
	}

	public void ejectCard() {
		
		System.out.println("Your card is ejected");
		atmMachine.setATMState(atmMachine.getNoCardState());
		
	}

	public void requestCash(int cashToWithdraw) {
		
		if(cashToWithdraw > atmMachine.cashInMachine){
			
			System.out.println("You don't have that much cash available");
			System.out.println("Your card is ejected");
			atmMachine.setATMState(atmMachine.getNoCardState());
			
		} else {
			
			System.out.println(cashToWithdraw + " is provided by the machine");
			atmMachine.setCashInMachine(atmMachine.cashInMachine - cashToWithdraw);
			
			System.out.println("Your card is ejected");
			atmMachine.setATMState(atmMachine.getNoCardState());
			
			if(atmMachine.cashInMachine <= 0){ 
				
				atmMachine.setATMState(atmMachine.getNoCashState());
				
			}
		} 
	}

	public void insertPin(int pinEntered) {
		
		System.out.println("You already entered a PIN");
		
	}	
}

NOCASH.JAVA

public class NoCash implements ATMState {
	
	ATMMachine atmMachine;
	
	public NoCash(ATMMachine newATMMachine){
		
		atmMachine = newATMMachine;
		
	}

	public void insertCard() {
		
		System.out.println("We don't have any money");
		System.out.println("Your card is ejected");
		
	}

	public void ejectCard() {
		
		System.out.println("We don't have any money");
		System.out.println("There is no card to eject");
		
	}

	public void requestCash(int cashToWithdraw) {
		
		System.out.println("We don't have any money");
		
	}

	public void insertPin(int pinEntered) {
		
		System.out.println("We don't have any money");
		
	}	
}

TESTATMMACHINE.JAVA

public class TestATMMachine {
	
	public static void main(String[] args){
		
		ATMMachine atmMachine = new ATMMachine();
		
		atmMachine.insertCard();
		
		atmMachine.ejectCard();
		
		atmMachine.insertCard();
		
		atmMachine.insertPin(1234);
		
		atmMachine.requestCash(2000);
		
		atmMachine.insertCard();
		
		atmMachine.insertPin(1234);
		
	}	
}

40 Responses to “State Design Pattern Tutorial”

  1. mr.roshik says:

    hi how r you ? could you please tell me how to add an twitter account for twitter stream?

  2. John says:

    No Comments??

    • admin says:

      My website isn’t very popular, but I enjoy it with the few in my community 🙂

      • Sno says:

        Great things are rarely appreciated just the nature of the beast. The site is awesome. The game I’m trying to make uses states so i wanted to understand them better. So i watched this twice. good vid!

        • Sno says:

          I should have said fully appreciated. There definately seems to be alot of people here that do. Just find it hard to believe this site is’nt popular thats all.

          I was wondering if you could touch on hierarchical state machines if you get time.

        • admin says:

          Thank you 🙂 I enjoyed covering design patterns and I’ll revisit them in my refactoring tutorial which should be starting very soon. Thanks for stopping by my site

  3. atul says:

    Hello,
    nice tutorial
    I watched some of your previous tutorial and after reading about state design pattern , it came to my mind that we can include singleton design pattern to ATMMachine , so that not more one instance of ATMMachine() is created .This is also true in real world Atm application.
    is my thinking correct or am i thinking too much ?? 😛 😉

  4. yasar says:

    Sir Thanks a Lot For Great work you are doing.

    the way you are teaching is very easy to understand

    i don’t have so much money to go and learn java outside

    you are saving me lots and lots money

    • Derek Banas says:

      You are very very welcome 🙂 I as well didn’t have money to attend college and I made this site for people like you and I. I’m extremely happy to be able to provide a free education to the best of my ability.

  5. navid says:

    hi, thanks for the great tutorial
    i am making a ATM simulation . i am also using uml diagram . now that i have a class diagram i wanted to use the state pattern for it, but my coding is completely different from yours, can you help me ?

    • Derek Banas says:

      You’re welcome 🙂 This isn’t by any means the only way to create an ATM simulator. I’m not the type of person that says if you don’t do it my way you are wrong. If your way works then go with that. Feel free to ask questions, but if your code works and it is understandable then it is good in my opinion

      • navid says:

        Thanks for the reply.
        yes it works,but i can’t figure out a way to use state pattern in my UML class or my coding. that is my problem.because i have totally different classes.but still i will try to make it work.

  6. boris says:

    i love every single video that you have..so clear..thank you

  7. Michael says:

    You are my hero! 🙂

  8. Rafi says:

    very nice …
    you are the real Hero…

    I am requesting you.. can u upload web services plz…

    thank u….

  9. Kapil says:

    You have always been providing in depth and concise information, through very simple demos .. I really appreciate your good work on Design pattern . Kindly keep this good work up and running as you are obviously helping less knowledgeable people like me 🙂
    Thanks again

    • Derek Banas says:

      Thank you very much 🙂 I do my best to make everything understandable and interesting. Those are my main goals. I also struggled with the same bad textbooks that you probably have seen. I always wanted to do what ever I could to make these topics understandable.

  10. Dale says:

    Nice clean code, very good example….

    If I was to adapt the structure for something else…how do you feel would be the best way to incorporate something like a sub state in one of those states….say

    Counting state (increments until hits a target then changes state to Execute state (which allows you to do something, then reverts back to Counting until reaches a target again)

    Thanks 🙂

    • Dale says:

      Also the execute state does not preventing other items counting so several items counting in parallel, but cannot do anything until reached the target…but the user could choose to do nothing on one of the items so a later item could reach its target and the user could choose to do something with it before an item which hit its target earlier…if that makes sense

      🙂

  11. Mike says:

    great job !

    clear and useful 🙂

  12. Xavier says:

    Hi!! I’m C++ programmer, but your video tutorials for patterns are the best I’ve ever seen so far, so I’ve been following them, and I review them whenever I need to implement a pattern (for C++).

    Your explanations and source code are clean and easy to digest; however, I think a FSM diagram is needed in order to see when and why a transition is needed. Of course reading the source code gives that information, but you know, an image says more than a thousand words.

    Thank you and keep going!!

    • Derek Banas says:

      Hi Xavier,

      Thank you 🙂 It is nice to know that these tutorials are helping people. Especially if you like them enough to use as a reference. that is very cool. Yes I should go in a see if I can add anything to improve them. I’ll set some time aside soon.

      Derek

  13. Rojun Itu says:

    Hi,

    I’m studying CS in a Finnish uni, and took a design patterns course. After banging my head against the wall with the aid of 3-4 books ( a bit like this: http://www.youtube.com/watch?v=7qHL2PSpecI&t=3m02s ) I discovered your tutorials and I am more than glad for this coincidence.

    Writing the code alongside your tutorials is the best learning routine I’ve come up with so far. It shortened the learning experience of getting from theory to practice from 2-10hrs with the book to 15-30mins with your tutorial. It’s such a good method, I’m undecided on should I tell everyone about this or should I keep it my secret for the time being 😉

    To other ones that might be reading this, GoF’s book, Head First Design Patterns and maybe Java Design Patterns vol 1 with Derek’s tutorials is a guaranteed way to go about these patterns – in case that the tutorials left any questions. Just sharing..

    A huge thanks to you!

    I’ll be checking your uml, refactoring and android dev tutorials next.

    -r

    • Derek Banas says:

      Hi,

      Thank you for all of the nice compliments 🙂 I very much appreciate them. I did my best to translate the GOF book into a series of easy to understand videos. I struggled with them as well many years ago.

      I wish you all the best
      Derek

  14. prasanth says:

    Thank you very much … very nice tutorial on design patterns

  15. Reza says:

    Derek,
    Thank you for all of the good work you put to create these videos. Could you please provide UML class diagram for this video? I don’t know how I can show ATMState hasCard, noCard, hasCorrectPin, atmOutOfMoney in ATMMachine class

Leave a Reply

Your email address will not be published.

Google+