Table of Contents

State pattern

State.java

package state;
 
abstract public class State {
    ChatClient context;
 
    State(ChatClient context){
        this.context = context;
    }
 
    void setContext(ChatClient newContext){
        context = newContext;
    }
    abstract void write(String message);
    abstract void connect(String address);
}

ConnectedState.java

package state;
 
public class ConnectedState extends State {
 
    public ConnectedState(ChatClient context) {
        super(context);
    }
 
    @Override
    void write(String message) {
        context.stream.println(message);
    }
 
    @Override
    void connect(String address) {
        //throw new RuntimeException("already connected");
    }
}

DisconnectedState.java

package state;
 
public class DisconnectedState extends State {
    public DisconnectedState(ChatClient context) {
        super(context);
    }
 
    @Override
    void write(String message) {
        throw new RuntimeException("not connected");
    }
 
    @Override
    void connect(String address) {
        System.out.println("Connecting...");
        context.stream = System.out;
        context.setState(new ConnectedState(context));
    }
}

ChatClient.java

package state;
 
import java.io.PrintStream;
 
public class ChatClient {
    State state;
    PrintStream stream;
    public ChatClient(){
        state = new DisconnectedState(this);
    }
 
    void setState(State newstate){
        state = newstate;
    }
 
    public void write(String message){
        state.write(message);
    }
 
    public void connect(){
        state.connect("tady by mel byt treba hostname");
    }
}

Main.java

package state;
 
public class Main {
    public static void main(String[] args) {
        ChatClient client = new ChatClient();
        //zkuste client.write("ahoj");
        client.connect();
        client.connect();
        client.write("ahoj");
    }
}