SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
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?

Más contenido relacionado

Destacado

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
 

Destacado (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 a 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
 

Similar a 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
 

Más 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
 

Más 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
 

Último

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 

Último (20)

ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 

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