SlideShare une entreprise Scribd logo
1  sur  30
Télécharger pour lire hors ligne
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?

Contenu connexe

En vedette

Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questionsUmar 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 javaAditya Bhuyan
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questionsjinaldesailive
 
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 OverviewLars 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 UserZeroTurnaround
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
Visitor Pattern
Visitor PatternVisitor Pattern
Visitor PatternIder Zheng
 
Design Pattern introduction
Design Pattern introductionDesign Pattern introduction
Design Pattern introductionneuros
 
Java EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsJava EE Revisits GoF Design Patterns
Java EE Revisits GoF Design PatternsMurat 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 editorSantosh Kumar Kar
 
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 - CoreDzmitry 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-JavaKasun Indrasiri
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The BasicsJeff Fox
 

En vedette (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
 

Similaire à Java Design Patterns: The State Pattern

Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsTomek Kaczanowski
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsTomek Kaczanowski
 
DevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The CoversDevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The CoversSimon Maple
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statementmanish kumar
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
Unit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterUnit testing CourseSites Apache Filter
Unit testing CourseSites Apache FilterWayan Wira
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition StructurePRN USM
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkDavid Rajah Selvaraj
 
Androidの本当にあった怖い話
Androidの本当にあった怖い話Androidの本当にあった怖い話
Androidの本当にあった怖い話Yusuke Yamamoto
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 

Similaire à 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
 

Plus de 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 pandaAntony Quinn
 
Bioinformatics Data Analysis: InterPro
Bioinformatics Data Analysis: InterProBioinformatics Data Analysis: InterPro
Bioinformatics Data Analysis: InterProAntony 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 EngineerAntony Quinn
 
Bioinformatics UX Design: InterPro
Bioinformatics UX Design: InterProBioinformatics UX Design: InterPro
Bioinformatics UX Design: InterProAntony 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 SchoolAntony Quinn
 

Plus de 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
 

Dernier

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Dernier (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

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();