在Java中,优雅地管理状态可以通过以下几种方法实现:
public enum State {
INITIAL,
RUNNING,
PAUSED,
STOPPED;
}
public interface State {
void handle(Context context);
}
public class InitialState implements State {
@Override
public void handle(Context context) {
// Perform actions for initial state
context.setState(new RunningState());
}
}
public class Context {
private State state;
public Context() {
state = new InitialState();
}
public void setState(State state) {
this.state = state;
}
public void request() {
state.handle(this);
}
}
import java.util.ArrayList;
import java.util.List;
public interface Observer {
void update(Subject subject);
}
public class ConcreteObserver implements Observer {
@Override
public void update(Subject subject) {
// Handle state change
}
}
public interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(this);
}
}
public void changeState() {
// Change state
notifyObservers();
}
}
public interface StateManager {
void handleStateChange(Context context);
}
public class StateManagerImpl implements StateManager {
@Override
public void handleStateChange(Context context) {
// Handle state change
}
}
public class Context {
private StateManager stateManager;
public Context(StateManager stateManager) {
this.stateManager = stateManager;
}
public void changeState() {
stateManager.handleStateChange(this);
}
}
通过使用这些方法,你可以在Java中优雅地管理状态,提高代码的可读性、可维护性和可扩展性。