Added state pattern sample

This commit is contained in:
Ilkka Seppala 2014-08-23 08:47:44 +03:00
parent b3d48cc4df
commit 9166d47ffc
7 changed files with 123 additions and 0 deletions

View File

@ -37,6 +37,7 @@
<module>mediator</module>
<module>memento</module>
<module>observer</module>
<module>state</module>
</modules>
<build>

23
state/pom.xml Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.iluwatar</groupId>
<artifactId>state</artifactId>
<version>1.0-SNAPSHOT</version>
<name>state</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,21 @@
package com.iluwatar;
public class AngryState implements State {
private Mammoth mammoth;
public AngryState(Mammoth mammoth) {
this.mammoth = mammoth;
}
@Override
public void observe() {
System.out.println(String.format("%s is furious!", mammoth));
}
@Override
public void onEnterState() {
System.out.println(String.format("%s gets angry!", mammoth));
}
}

View File

@ -0,0 +1,16 @@
package com.iluwatar;
public class App
{
public static void main( String[] args )
{
Mammoth mammoth = new Mammoth();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
mammoth.timePasses();
mammoth.observe();
}
}

View File

@ -0,0 +1,32 @@
package com.iluwatar;
public class Mammoth {
private State state;
public Mammoth() {
state = new PeacefulState(this);
}
public void timePasses() {
if (state.getClass().equals(PeacefulState.class)) {
changeStateTo(new AngryState(this));
} else {
changeStateTo(new PeacefulState(this));
}
}
private void changeStateTo(State newState) {
this.state = newState;
this.state.onEnterState();
}
@Override
public String toString() {
return "The mammoth";
}
public void observe() {
this.state.observe();
}
}

View File

@ -0,0 +1,21 @@
package com.iluwatar;
public class PeacefulState implements State {
private Mammoth mammoth;
public PeacefulState(Mammoth mammoth) {
this.mammoth = mammoth;
}
@Override
public void observe() {
System.out.println(String.format("%s is calm and peaceful.", mammoth));
}
@Override
public void onEnterState() {
System.out.println(String.format("%s calms down.", mammoth));
}
}

View File

@ -0,0 +1,9 @@
package com.iluwatar;
public interface State {
void onEnterState();
void observe();
}