Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

State design pattern #12

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,32 @@
# DesignPatternsJava9
This repo consists Gang of Four Design patterns code on Java 9. Each branch in the repository has code of 1 design pattern. Switch repository to try out different design patterns.
# What is State Design Pattern
State pattern allows an object to behave differently depending on its internal state.

## Diagram
![Diagram](https://github.com/premaseem/DesignPatternsJava9/blob/state-pattern/diagrams/State-Design-Pattern-class-diagram.jpeg "Diagram")

![Diagram](https://github.com/premaseem/DesignPatternsJava9/blob/state-pattern/diagrams/State-Design-Pattern-generic.jpeg "Diagram")

![Diagram](https://github.com/premaseem/DesignPatternsJava9/blob/state-pattern/diagrams/StatePatternSequenceDiagram.png "Diagram")

### When to use State Design Pattern
When the behaviour of an object should be influenced by it's state, and when complex conditions tie object behaviour to it's state.

### Learn Design Patterns with Java by Aseem Jain
This repository contains working project code used in video Course by Packt Publication with title "Learn Design Patterns with Java " authored by "Aseem Jain".

### Course link:
https://www.packtpub.com/application-development/learn-design-patterns-java-9-video

### ![ http://in.linkedin.com/in/premaseem](https://github.com/premaseem/DesignPatternsJava9/blob/master/linkedin.png "http://in.linkedin.com/in/premaseem") Profile: http://in.linkedin.com/in/premaseem

### Authors blog on design patterns:
https://premaseem.wordpress.com/category/computers/design-patterns/

### Software Design pattern community face book page:
https://www.facebook.com/DesignPatternGuru/

### Note:
* This code base will work on Java 9 and above versions.
* `diagrams` folders carry UML diagrams.
* `pattern` folder has code of primary example.
* `patternBonus` folder has code of secondary or bonus example.
Binary file added diagrams/State-Design-Pattern-class-diagram.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added diagrams/State-Design-Pattern-generic.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added diagrams/StatePatternSequenceDiagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 0 additions & 13 deletions pattern/src/com/premaseem/Client.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.premaseem.statePattern;

/*
@author: Aseem Jain
@title: Design Patterns with Java 9
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
*/

import java.util.Scanner;

public class ClientForMedicalTreatment {

public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
String repeatRunFlag = "yes";

System.out.println("This is State Pattern example where in treatment would be dependent on the state of the patient ) ");
TreatmentContext context = new TreatmentContext();

while (repeatRunFlag.equalsIgnoreCase("yes")) {
// method takes patients state input
takePatientStateInput(context);

System.out.println("Patient's State is - " + context.getState().getClass().getSimpleName() + ". Choose line of treatment ...");
System.out.println(" Press 1 for admitting in ICU");
System.out.println(" Press 2 for prescribing general Medicine ");
System.out.println(" Press 3 for supply of Oxygen");
System.out.println(" Press 4 for supply of Normal food");
System.out.println(" Press 5 for recommending a walk ");

int treatmentType = scan.nextInt();

switch (treatmentType) {
case 1:
context.admitInICU();
break;
case 2:
context.prescribeGeneralMedicine();
break;
case 3:
context.supplyOxygen();
break;
case 4:
context.supplyNormalFood();
break;

case 5:
context.recommendWalking();
break;
}

System.out.println(" ## State changed to: " + context.getState().getClass().getSimpleName());
System.out.println("Press yes for further treatment and No to EXIT .... ");
try {
repeatRunFlag = scan.next();
} catch (Exception e) {
repeatRunFlag = "No";
}
}
}

private static void takePatientStateInput (TreatmentContext context) {
Scanner scan = new Scanner(System.in);
System.out.println("Choose state of patient before starting treatment ");
System.out.println(" Press 1 for unstable state patient");
System.out.println(" Press 2 for stable state patient ");
int entType = scan.nextInt();

switch (entType) {
case 1:
context.setState(context.unStablePatientState);
break;
case 2:
context.setState(context.stablePatientState);
break;
}
}
}
97 changes: 97 additions & 0 deletions pattern/src/com/premaseem/statePattern/PatientHealthState.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package com.premaseem.statePattern;

/*
@author: Aseem Jain
@title: Design Patterns with Java 9
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
*/

public interface PatientHealthState {

void supplyOxygen ();

void supplyOralFood ();

void recommendWalking ();

void prescribeGeneralMedicine ();

void admitInICU ();
}

class StablePatientState implements PatientHealthState {

private TreatmentContext context;

public StablePatientState (TreatmentContext context) {
this.context = context;
}

@Override
public void supplyOxygen () {
System.out.println("Stable patient might become unstable if oxygen is forced fed. ");
context.setState(context.unStablePatientState);
}

@Override
public void supplyOralFood () {
System.out.println(" Oral food will help faster recovery for Stable Patients. ");
context.setState(context.stablePatientState);
}

@Override
public void recommendWalking () {
System.out.println(" Stable Patients should walk for about 1 mile each day. ");
context.setState(context.stablePatientState);
}

@Override
public void prescribeGeneralMedicine () {
System.out.println(" will help in improvement ");
context.setState(context.stablePatientState);
}

@Override
public void admitInICU () {
System.out.println(" Stable patient might become unstable if forced admit in ICU ");
context.setState(context.unStablePatientState);
}
}

class UnStablePatientState implements PatientHealthState {

private TreatmentContext context;

public UnStablePatientState (TreatmentContext context) {
this.context = context;
}

@Override
public void supplyOxygen () {
System.out.println("UnStable patient do need oxygen, will help in getting stable ");
context.setState(context.stablePatientState);
}

@Override
public void supplyOralFood () {
System.out.println(" supply blood and liquids, will help in getting stable ");
context.setState(context.stablePatientState);
}

@Override
public void recommendWalking () {
System.out.println("Not needed until patient becomes stable ");
context.setState(context.unStablePatientState);
}

@Override
public void prescribeGeneralMedicine () {
System.out.println(" needs advance medicine ");
}

@Override
public void admitInICU () {
System.out.println(" Intensive care is needed, will help in getting stable ");
context.setState(context.stablePatientState);
}
}
16 changes: 16 additions & 0 deletions pattern/src/com/premaseem/statePattern/PatternDescription.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
The state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to encapsulate varying behavior for the same routine based on an object's state object. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements.
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

Problem solved by State pattern

A monolithic object's behavior is a function of its state, and it must change its behavior at run-time depending on that state. Or, an application is characterixed by large and numerous case statements that vector flow of control based on the state of the application.

Different between State and Strategy
Strategy Pattern is used when the whole algorithm is changed to another algorithm and the client is responsible for that, whereas, in State Pattern, the class itself manages the strategy based on the state.

Two patterns are pretty similar in practice, and the defining difference between them tends to vary depending on who you ask. Some popular choices are:

States store a reference to the context object that contains them. Strategies do not.
States are allowed to replace themselves (IE: to change the state of the context object to something else), while Strategies are not.
Strategies are passed to the context object as parameters, while States are created by the context object itself.
Strategies only handle a single, specific task, while States provide the underlying implementation for everything (or most everything) the context object does.
45 changes: 45 additions & 0 deletions pattern/src/com/premaseem/statePattern/TreatmentContext.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.premaseem.statePattern;

/*
@author: Aseem Jain
@title: Design Patterns with Java 9
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
*/

public class TreatmentContext {

PatientHealthState state;
StablePatientState stablePatientState = new StablePatientState(this);
UnStablePatientState unStablePatientState = new UnStablePatientState(this);


public PatientHealthState getState () {
return state;
}

public void setState (PatientHealthState state) {
this.state = state;
}


void prescribeGeneralMedicine () {
state.prescribeGeneralMedicine();
}

void admitInICU () {
state.admitInICU();
}

void supplyOxygen () {
state.supplyOxygen();
}

void supplyNormalFood () {
state.supplyOralFood();
}

void recommendWalking () {
state.recommendWalking();
}

}
13 changes: 0 additions & 13 deletions patternBonus/src/com/premaseem/Client.java

This file was deleted.