added state pattern example

This commit is contained in:
Louis Heredero 2024-10-14 10:46:20 +02:00
parent 6acdcaffa7
commit 876ce99c77
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,34 @@
package learn.simple_state;
public class Context {
private State onState;
private State offState;
private State currentState;
public Context() {
onState = new OnState(this);
offState = new OffState(this);
currentState = offState;
}
public void setCurrentState(State currentState) {
this.currentState = currentState;
}
public State getOffState() {
return offState;
}
public State getOnState() {
return onState;
}
public void on() {
currentState.on();
}
public void off() {
currentState.off();
}
}

View File

@ -0,0 +1,12 @@
package learn.simple_state;
public class Main {
public static void main(String[] args) {
Context context = new Context();
context.off();
context.off();
context.on();
context.on();
context.off();
}
}

View File

@ -0,0 +1,20 @@
package learn.simple_state;
public class OffState implements State {
private Context context;
public OffState(Context context) {
this.context = context;
}
@Override
public void on() {
context.setCurrentState(context.getOnState());
System.out.println("Transition to on");
}
@Override
public void off() {
System.out.println("Already off");
}
}

View File

@ -0,0 +1,20 @@
package learn.simple_state;
public class OnState implements State {
private Context context;
public OnState(Context context) {
this.context = context;
}
@Override
public void on() {
System.out.println("Already on");
}
@Override
public void off() {
context.setCurrentState(context.getOffState());
System.out.println("Transition to off");
}
}

View File

@ -0,0 +1,6 @@
package learn.simple_state;
public interface State {
void on();
void off();
}