SlideShare a Scribd company logo
1
State Pattern
Antony Quinn
2
Structure
 Intent
 Example
 UML structure
 Benefits and drawbacks
 Exercise
3
Intent
 Allow an object to alter its behaviour
when its internal state changes. The
object will appear to change its class.
 Also known as
Objects for states
4
Example: Cell cycle
 Our system has 5 states:
Start
Interphase
Mitosis
Cytokinesis
End
 It has 2 events:
advance
grow
5
Sample Code
6
public class Cell {
private CellState state = new StartState();
public void grow() {
state.grow(this);
}
public void advance() {
state.advance(this);
}
// Package-private
void setState(CellState newState) {
if (state != newState) {
System.out.println(toString(state) + " -> " + toString(newState));
state = newState;
}
}
7
interface CellState {
/** @throws IllegalStateException*/
public void grow(Cell cell);
/** @throws IllegalStateException*/
public void advance(Cell cell);
}
class StartState implements CellState {
public void grow(Cell cell) {
throw new IllegalStateException();
}
public void advance(Cell cell) {
cell.setState(new InterphaseState());
}
}
8
class InterphaseState implements CellState {
public void grow(Cell cell) {
cell.makeProtein();
}
public void advance(Cell cell) {
cell.replicateDNA();
cell.setState(new MitosisState());
}
}
9
class MitosisState implements CellState {
public void grow(Cell cell) {
throw new IllegalStateException();
}
public void advance(Cell cell) {
cell.divideNucleus();
cell.setState(new CytokinesisState());
}
}
10
class CytokinesisState implements CellState {
public void grow(Cell cell) {
throw new IllegalStateException();
}
public void advance(Cell cell) {
cell.divideCytoplasm();
cell.setState(new EndState());
}
}
11
class EndState implements CellState {
public void grow(Cell cell) {
throw new IllegalStateException("Dead cells can't grow");
}
public void advance(Cell cell) {
throw new IllegalStateException("Dead cells can't advance");
}
}
12
public class TestCell {
public static void main(String[] args) {
Cell cell = new Cell();
cell.advance(); // Interphase
cell.grow();
cell.grow();
cell.advance(); // Mitosis
cell.advance(); // Cytokinesis
cell.advance(); // End
cell.grow(); // error
}
}
13
Applicability
 Use the State pattern when
An object's behaviour depends on its
state and must change its behaviour at
run-time depending on that state
Operations have large, multipart
conditional statements that depend on
the object's state, typically switch or
if-else-if constructs
14
Structure
15
Consequences
 Benefits
Localises state-specific behaviour and
partitions behaviour for different states
Makes state transitions explicit
State objects can be shared
 Drawbacks
Lots of classes
16
Known Uses
 Java
JTable selection
Java Media Framework (JMF)
 EBI
UniProt automated annotation (Ernst,
Dani and Michael)
17
Question
 At what level of complexity would you
refactor code to use the State Pattern?
18
Exercise
Design a Frog class that
contains the state
machine on the left.
19
Solution
 Use an abstract class for common
functionality (but in general we “favor
composition over inheritance” - see the
Strategy pattern)
 Start state is transitional, so we can skip it.
20
Solution 1
21
Alternative solution
 Could instead let the state's methods return the
new state
 Advantages:
No dependency between FrogState and Frog
(looser coupling)
setState is private in Frog
22
Solution 2
23
public class Frog {
private FrogState state = new EmbryoState();
public void develop() {
setState(state.develop());
}
public void eat() {
setState(state.eat());
}
public void die() {
setState(state.die());
}
private void setState(FrogState newState) {
if (state != newState) {
System.out.println(state + " -> " + newState);
state = newState;
24
abstract class FrogState {
public FrogState develop() {
throw new IllegalStateException();
}
public FrogState eat() {
throw new IllegalStateException();
}
public FrogState die() {
return new EndState();
}
}
25
class EmbryoState extends FrogState {
public FrogState develop() {
return new TadpoleState();
}
}
class TadpoleState extends FrogState {
public FrogState develop() {
return new AdultState();
}
public FrogState eat() {
System.out.println("Eating algae.");
return this;
}
}
26
class AdultState extends FrogState {
public FrogState eat() {
System.out.println("Eating flies.");
return this;
}
}
class EndState extends FrogState {
public FrogState die() {
throw new IllegalStateException("Dead frogs can't die.");
}
}
27
public class TestFrog {
public static void main(String[] args) {
Frog frog = new Frog(); // Embryo
frog.develop(); // Tadpole
frog.eat();
frog.develop(); // Adult
frog.eat();
frog.eat();
frog.die(); // Dead frog
frog.die(); // Error
}
}
28
import junit.framework.TestCase;
public class EmbryoStateTest extends TestCase {
public void testDevelop() {
FrogState state = new EmbryoState();
FrogState nextState = state.develop();
assertEquals(TadpoleState.class, nextState.getClass());
}
public void testEat() {
FrogState state = new EmbryoState();
try {
FrogState nextState = state.eat();
fail("Embryos can't eat.");
}
catch (Exception e) {
assertEquals(IllegalStateException.class, e.getClass());
29
import junit.framework.TestCase;
public class TadpoleStateTest extends TestCase {
public void testEat() {
FrogState state = new TadpoleState();
FrogState nextState = state.eat();
assertEquals(TadpoleState.class, nextState.getClass());
}
public void testDevelop() {
FrogState state = new TadpoleState();
FrogState nextState = state.develop();
assertEquals(AdultState.class, nextState.getClass());
}
public void testDie() {
FrogState state = new TadpoleState();
FrogState nextState = state.die();
30
Any questions?

More Related Content

Viewers also liked

Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
Umar Ali
 
Java Design Pattern Interview Questions
Java Design Pattern Interview QuestionsJava Design Pattern Interview Questions
Java Design Pattern Interview Questionsjbashask
 
Design patterns through java
Design patterns through javaDesign patterns through java
Design patterns through java
Aditya Bhuyan
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questions
jinaldesailive
 
Iterator Pattern Baljeet Sandhu 20060621
Iterator Pattern Baljeet Sandhu 20060621Iterator Pattern Baljeet Sandhu 20060621
Iterator Pattern Baljeet Sandhu 20060621melbournepatterns
 
Eclipse e4 Overview
Eclipse e4 OverviewEclipse e4 Overview
Eclipse e4 Overview
Lars Vogel
 
Getting Started with IntelliJ IDEA as an Eclipse User
Getting Started with IntelliJ IDEA as an Eclipse UserGetting Started with IntelliJ IDEA as an Eclipse User
Getting Started with IntelliJ IDEA as an Eclipse User
ZeroTurnaround
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
Varun Arora
 
Composite pattern
Composite patternComposite pattern
Composite pattern
Shakil Ahmed
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor Pattern
Ider Zheng
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
Kanda Runapongsa Saikaew
 
Design Pattern introduction
Design Pattern introductionDesign Pattern introduction
Design Pattern introduction
neuros
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF Design Patterns
Murat Yener
 
Writing simple web services in java using eclipse editor
Writing simple web services in java using eclipse editorWriting simple web services in java using eclipse editor
Writing simple web services in java using eclipse editor
Santosh Kumar Kar
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
Shakil Ahmed
 
External Data Access with jQuery
External Data Access with jQueryExternal Data Access with jQuery
External Data Access with jQueryDoncho Minkov
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
Kasun Indrasiri
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 

Viewers also liked (20)

Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
 
Java Design Pattern Interview Questions
Java Design Pattern Interview QuestionsJava Design Pattern Interview Questions
Java Design Pattern Interview Questions
 
Design patterns through java
Design patterns through javaDesign patterns through java
Design patterns through java
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questions
 
Iterator Pattern Baljeet Sandhu 20060621
Iterator Pattern Baljeet Sandhu 20060621Iterator Pattern Baljeet Sandhu 20060621
Iterator Pattern Baljeet Sandhu 20060621
 
Eclipse e4 Overview
Eclipse e4 OverviewEclipse e4 Overview
Eclipse e4 Overview
 
Getting Started with IntelliJ IDEA as an Eclipse User
Getting Started with IntelliJ IDEA as an Eclipse UserGetting Started with IntelliJ IDEA as an Eclipse User
Getting Started with IntelliJ IDEA as an Eclipse User
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor Pattern
 
Composite Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design Pattern
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
Design Pattern introduction
Design Pattern introductionDesign Pattern introduction
Design Pattern introduction
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF Design Patterns
 
Writing simple web services in java using eclipse editor
Writing simple web services in java using eclipse editorWriting simple web services in java using eclipse editor
Writing simple web services in java using eclipse editor
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
External Data Access with jQuery
External Data Access with jQueryExternal Data Access with jQuery
External Data Access with jQuery
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 

Similar to Java Design Patterns: The State Pattern

Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
Mavoori Soshmitha
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
Марія Русин
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
Tiago de Freitas Lima
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
Nalinee Choudhary
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
Sunil kumar Mohanty
 
DevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The CoversDevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The Covers
Simon Maple
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
manish kumar
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
Nikunj Parekh
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
Nikunj Parekh
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterUnit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
Wayan Wira
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
PRN USM
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Qi4j
Qi4j Qi4j
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
David Rajah Selvaraj
 
Androidの本当にあった怖い話
Androidの本当にあった怖い話Androidの本当にあった怖い話
Androidの本当にあった怖い話Yusuke Yamamoto
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 

Similar to Java Design Patterns: The State Pattern (20)

3 j unit
3 j unit3 j unit
3 j unit
 
Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
DevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The CoversDevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The Covers
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterUnit testing CourseSites Apache Filter
Unit testing CourseSites Apache Filter
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Qi4j
Qi4j Qi4j
Qi4j
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
Androidの本当にあった怖い話
Androidの本当にあった怖い話Androidの本当にあった怖い話
Androidの本当にあった怖い話
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

More from Antony Quinn

DNA Disco: Shake your booty, save the panda
DNA Disco: Shake your booty, save the pandaDNA Disco: Shake your booty, save the panda
DNA Disco: Shake your booty, save the panda
Antony Quinn
 
DNA Disco
DNA DiscoDNA Disco
DNA Disco
Antony Quinn
 
Bioinformatics Data Analysis: InterPro
Bioinformatics Data Analysis: InterProBioinformatics Data Analysis: InterPro
Bioinformatics Data Analysis: InterPro
Antony Quinn
 
Careers in Bioinformatics: Life as a Software Engineer
Careers in Bioinformatics: Life as a Software EngineerCareers in Bioinformatics: Life as a Software Engineer
Careers in Bioinformatics: Life as a Software Engineer
Antony Quinn
 
Bioinformatics UX Design: InterPro
Bioinformatics UX Design: InterProBioinformatics UX Design: InterPro
Bioinformatics UX Design: InterPro
Antony Quinn
 
Food Waste Hero: the Internet of Things Meets Behavioral Economics in School
Food Waste Hero: the Internet of Things Meets Behavioral Economics in SchoolFood Waste Hero: the Internet of Things Meets Behavioral Economics in School
Food Waste Hero: the Internet of Things Meets Behavioral Economics in School
Antony Quinn
 
Food Waste Hero
Food Waste HeroFood Waste Hero
Food Waste Hero
Antony Quinn
 

More from Antony Quinn (7)

DNA Disco: Shake your booty, save the panda
DNA Disco: Shake your booty, save the pandaDNA Disco: Shake your booty, save the panda
DNA Disco: Shake your booty, save the panda
 
DNA Disco
DNA DiscoDNA Disco
DNA Disco
 
Bioinformatics Data Analysis: InterPro
Bioinformatics Data Analysis: InterProBioinformatics Data Analysis: InterPro
Bioinformatics Data Analysis: InterPro
 
Careers in Bioinformatics: Life as a Software Engineer
Careers in Bioinformatics: Life as a Software EngineerCareers in Bioinformatics: Life as a Software Engineer
Careers in Bioinformatics: Life as a Software Engineer
 
Bioinformatics UX Design: InterPro
Bioinformatics UX Design: InterProBioinformatics UX Design: InterPro
Bioinformatics UX Design: InterPro
 
Food Waste Hero: the Internet of Things Meets Behavioral Economics in School
Food Waste Hero: the Internet of Things Meets Behavioral Economics in SchoolFood Waste Hero: the Internet of Things Meets Behavioral Economics in School
Food Waste Hero: the Internet of Things Meets Behavioral Economics in School
 
Food Waste Hero
Food Waste HeroFood Waste Hero
Food Waste Hero
 

Recently uploaded

Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
DhatriParmar
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
ShivajiThube2
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 

Recently uploaded (20)

Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 

Java Design Patterns: The State Pattern

  • 2. 2 Structure  Intent  Example  UML structure  Benefits and drawbacks  Exercise
  • 3. 3 Intent  Allow an object to alter its behaviour when its internal state changes. The object will appear to change its class.  Also known as Objects for states
  • 4. 4 Example: Cell cycle  Our system has 5 states: Start Interphase Mitosis Cytokinesis End  It has 2 events: advance grow
  • 6. 6 public class Cell { private CellState state = new StartState(); public void grow() { state.grow(this); } public void advance() { state.advance(this); } // Package-private void setState(CellState newState) { if (state != newState) { System.out.println(toString(state) + " -> " + toString(newState)); state = newState; } }
  • 7. 7 interface CellState { /** @throws IllegalStateException*/ public void grow(Cell cell); /** @throws IllegalStateException*/ public void advance(Cell cell); } class StartState implements CellState { public void grow(Cell cell) { throw new IllegalStateException(); } public void advance(Cell cell) { cell.setState(new InterphaseState()); } }
  • 8. 8 class InterphaseState implements CellState { public void grow(Cell cell) { cell.makeProtein(); } public void advance(Cell cell) { cell.replicateDNA(); cell.setState(new MitosisState()); } }
  • 9. 9 class MitosisState implements CellState { public void grow(Cell cell) { throw new IllegalStateException(); } public void advance(Cell cell) { cell.divideNucleus(); cell.setState(new CytokinesisState()); } }
  • 10. 10 class CytokinesisState implements CellState { public void grow(Cell cell) { throw new IllegalStateException(); } public void advance(Cell cell) { cell.divideCytoplasm(); cell.setState(new EndState()); } }
  • 11. 11 class EndState implements CellState { public void grow(Cell cell) { throw new IllegalStateException("Dead cells can't grow"); } public void advance(Cell cell) { throw new IllegalStateException("Dead cells can't advance"); } }
  • 12. 12 public class TestCell { public static void main(String[] args) { Cell cell = new Cell(); cell.advance(); // Interphase cell.grow(); cell.grow(); cell.advance(); // Mitosis cell.advance(); // Cytokinesis cell.advance(); // End cell.grow(); // error } }
  • 13. 13 Applicability  Use the State pattern when An object's behaviour depends on its state and must change its behaviour at run-time depending on that state Operations have large, multipart conditional statements that depend on the object's state, typically switch or if-else-if constructs
  • 15. 15 Consequences  Benefits Localises state-specific behaviour and partitions behaviour for different states Makes state transitions explicit State objects can be shared  Drawbacks Lots of classes
  • 16. 16 Known Uses  Java JTable selection Java Media Framework (JMF)  EBI UniProt automated annotation (Ernst, Dani and Michael)
  • 17. 17 Question  At what level of complexity would you refactor code to use the State Pattern?
  • 18. 18 Exercise Design a Frog class that contains the state machine on the left.
  • 19. 19 Solution  Use an abstract class for common functionality (but in general we “favor composition over inheritance” - see the Strategy pattern)  Start state is transitional, so we can skip it.
  • 21. 21 Alternative solution  Could instead let the state's methods return the new state  Advantages: No dependency between FrogState and Frog (looser coupling) setState is private in Frog
  • 23. 23 public class Frog { private FrogState state = new EmbryoState(); public void develop() { setState(state.develop()); } public void eat() { setState(state.eat()); } public void die() { setState(state.die()); } private void setState(FrogState newState) { if (state != newState) { System.out.println(state + " -> " + newState); state = newState;
  • 24. 24 abstract class FrogState { public FrogState develop() { throw new IllegalStateException(); } public FrogState eat() { throw new IllegalStateException(); } public FrogState die() { return new EndState(); } }
  • 25. 25 class EmbryoState extends FrogState { public FrogState develop() { return new TadpoleState(); } } class TadpoleState extends FrogState { public FrogState develop() { return new AdultState(); } public FrogState eat() { System.out.println("Eating algae."); return this; } }
  • 26. 26 class AdultState extends FrogState { public FrogState eat() { System.out.println("Eating flies."); return this; } } class EndState extends FrogState { public FrogState die() { throw new IllegalStateException("Dead frogs can't die."); } }
  • 27. 27 public class TestFrog { public static void main(String[] args) { Frog frog = new Frog(); // Embryo frog.develop(); // Tadpole frog.eat(); frog.develop(); // Adult frog.eat(); frog.eat(); frog.die(); // Dead frog frog.die(); // Error } }
  • 28. 28 import junit.framework.TestCase; public class EmbryoStateTest extends TestCase { public void testDevelop() { FrogState state = new EmbryoState(); FrogState nextState = state.develop(); assertEquals(TadpoleState.class, nextState.getClass()); } public void testEat() { FrogState state = new EmbryoState(); try { FrogState nextState = state.eat(); fail("Embryos can't eat."); } catch (Exception e) { assertEquals(IllegalStateException.class, e.getClass());
  • 29. 29 import junit.framework.TestCase; public class TadpoleStateTest extends TestCase { public void testEat() { FrogState state = new TadpoleState(); FrogState nextState = state.eat(); assertEquals(TadpoleState.class, nextState.getClass()); } public void testDevelop() { FrogState state = new TadpoleState(); FrogState nextState = state.develop(); assertEquals(AdultState.class, nextState.getClass()); } public void testDie() { FrogState state = new TadpoleState(); FrogState nextState = state.die();