[JAVA] Design pattern ~ State ~

1.First of all

Here is a summary of the ** State pattern ** in the GoF design pattern.

2. What is the State pattern?

--The English word State means ** state **. --The State pattern is a method that expresses a state as a class and expresses a "change of state" by switching classes **. --The GoF design patterns are classified as ** behavioral design patterns **.

3. Sample class diagram

State.PNG

4. Sample program

It is a safe management program that changes the operation of buttons depending on the day and night conditions.

4-1. Context interface

An interface that manages changes in the state of the safe and keeps in touch with the security center.

Context.java


public interface Context {
	//Time setting
	public abstract void setClock(int hour);
	//Change of state
	public abstract void changeState(State state);
	//Security Center Security Guard Call
	public abstract void callSecurityCenter(String msg);
	//Security center record
	public abstract void recordLog(String msg);
}

4-2. SafeFrame class

A class that implements the Context interface. It has a UI such as buttons and screen display.

SafeFrame.java


import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SafeFrame extends Frame implements ActionListener, Context {

	private TextField textClock = new TextField(60);
	private TextArea textScreen = new TextArea(10, 60);
	private Button buttonUse = new Button("Safe use");
	private Button buttonAlarm = new Button("emergency bell");
	private Button buttonPhone = new Button("Normal call");
	private Button buttonExit = new Button("End");

	private State state = DayState.getInstance();

	public SafeFrame(String title) {
		super(title);

		setBackground(Color.lightGray);
		setLayout(new BorderLayout());
		add(textClock, BorderLayout.NORTH);
		textClock.setEditable(false);
		add(textScreen, BorderLayout.CENTER);
		textScreen.setEditable(false);

		Panel panel = new Panel();
		panel.add(buttonUse);
		panel.add(buttonAlarm);
		panel.add(buttonPhone);
		panel.add(buttonExit);
		add(panel, BorderLayout.SOUTH);

		pack();
		show();

		buttonUse.addActionListener(this);
		buttonAlarm.addActionListener(this);
		buttonPhone.addActionListener(this);
		buttonExit.addActionListener(this);
	}

	//Come here when the button is pressed
	public void actionPerformed(ActionEvent e) {
		System.out.println(e.toString());
		if (e.getSource() == buttonUse) {
			//Safe use button
			state.doUse(this);
		} else if (e.getSource() == buttonAlarm) {
			//Emergency bell button
			state.doAlarm(this);
		} else if (e.getSource() == buttonPhone) {
			//Normal call button
			state.doPhone(this);
		} else if (e.getSource() == buttonExit) {
			//Finish button
			System.exit(0);
		} else {
			System.out.println("?");
		}
	}

	//Time setting
	public void setClock(int hour) {
		String clockstring = "The current time is";
		if (hour < 10) {
			clockstring += "0" + hour + ":00";
		} else {
			clockstring += hour + ":00";
		}
		System.out.println(clockstring);
		textClock.setText(clockstring);
		state.doClock(this, hour);
	}

	//Change of state
	public void changeState(State state) {
		System.out.println(this.state + "From" + state + "The state has changed.");
		this.state = state;
	}

	//Security Center Security Guard Call
	public void callSecurityCenter(String msg) {
		textScreen.append("call! " + msg + "\n");
	}

	//Security center record
	public void recordLog(String msg) {
		textScreen.append("record ... " + msg + "\n");
	}
}

4-3. State interface

An interface that shows the status of the safe.

State.java


public interface State {
	//Time setting
	public abstract void doClock(Context context, int hour);
	//Safe use
	public abstract void doUse(Context context);
	//emergency bell
	public abstract void doAlarm(Context context);
	//Normal call
	public abstract void doPhone(Context context);
}

4-4. DayState class

A class that implements the State interface. Represents the daytime condition.

DayState.java


public class DayState implements State {
	private static DayState singleton = new DayState();

	private DayState() {
	}

	public static State getInstance() {
		return singleton;
	}

	public void doClock(Context context, int hour) {
		if (hour < 9 || 17 <= hour) {
			context.changeState(NightState.getInstance());
		}
	}

	public void doUse(Context context) {
		context.recordLog("Safe use(Daytime)");
	}

	public void doAlarm(Context context) {
		context.callSecurityCenter("emergency bell(Daytime)");
	}

	public void doPhone(Context context) {
		context.callSecurityCenter("Normal call(Daytime)");
	}

	public String toString() {
		return "[Daytime]";
	}
}

4-5. NightState class

A class that implements the State interface. Represents the nighttime condition

NightState.java


public class NightState implements State {
	private static NightState singleton = new NightState();

	private NightState() {
	}

	public static State getInstance() {
		return singleton;
	}

	public void doClock(Context context, int hour) {
		if (9 <= hour && hour < 17) {
			context.changeState(DayState.getInstance());
		}
	}

	public void doUse(Context context) {
		context.callSecurityCenter("Emergency: Use the safe at night!");
	}

	public void doAlarm(Context context) {
		context.callSecurityCenter("emergency bell(Night)");
	}

	public void doPhone(Context context) {
		context.recordLog("Night call recording");
	}

	public String toString() {
		return "[Night]";
	}
}

4-6. Main class

This class performs the main processing.

Main.java


public class Main {
	public static void main(String[] args) {
		SafeFrame frame = new SafeFrame("State Sample");
		while (true) {
			for (int hour = 0; hour < 24; hour++) {
				frame.setClock(hour);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
		}
	}
}

4-7. Execution result

pg.png

5. Benefits

The policy of ** splitting and integrating ** is common in programming. The State pattern represents a state as a class. Each concrete state is expressed as a separate class and divided. While implementing DayState, programmers no longer need to be aware of other classes (NightState). In the sample program, there were only two states, but the State pattern will be effective when there are more states.

  1. GitHub

7. List of design patterns

-** GoF design pattern summary **

8. Reference

This article and sample program were created based on the following books.

-** Introduction to design patterns learned in Java language **

It was very easy to understand and I learned a lot. Thank you. The detailed explanations of the design patterns and sample programs are written, so please take a look at the books as well.

Recommended Posts

Design pattern ~ State ~
Design pattern ~ Builder ~
Design pattern ~ Visitor ~
Design pattern ~ Proxy ~
Design pattern ~ Strategy ~
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (2): Builder
Design pattern (1): AbstractFactory
Design pattern ~ Command ~
Design pattern ~ Iterator ~
Design pattern ~ Facade ~
Design pattern ~ Bridge ~
Design pattern ~ Mediator ~
Design pattern ~ Decorator ~
Design pattern ~ Interpreter ~
Design pattern ~ Observer ~
Design pattern ~ Prototype ~
Design pattern ~ Memento ~
Design pattern ~ Adapter ~
Design pattern ~ Flyweight ~
Design pattern ~ Factory Method ~
Design pattern ~ Abstract Factory ~
GoF design pattern summary
Design pattern ~ Template Method ~
Java design pattern summary
Design pattern ~ Chain of Responsibility ~
[Design pattern] Java core library
Ruby design pattern template method pattern memo
C # chewed design pattern: Template Method
Application example of design pattern (No. 1)
Java beginner design pattern (Factory Method pattern)
Prototype pattern
Memento Pattern
What a Strategy pattern Factory, not a State
Mediator pattern
Iterator pattern
Composite pattern
Observer Pattern
Builder pattern
Bridge Pattern
Command Pattern
Builder Pattern
Strategy pattern
Iterator Pattern
Visitor pattern
Adapter Pattern
Proxy Pattern
Strategy Pattern
Composite Pattern
Singleton Pattern
Singleton pattern
Prototype Pattern
[Design pattern] Common logic with Template Method
Facade Pattern
Decorator pattern
Flyweight Pattern
Decorator Pattern
Mediator Pattern
I studied the State pattern and the Strategy pattern
Facade pattern