设计模式实战:任务调度系统的设计与实现
import java.util.ArrayList;
import java.util.List;
// 观察者接口
interface Observer {
void update(String message);
}
// 被观察者接口
interface Subject {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers(String message);
}
// 任务类
class Task implements Subject {
private List<Observer> observers = new ArrayList<>();
private State state;
private String name;
public Task(String name) {
this.name = name;
this.state = new PendingState(); // 初始状态为待处理
}
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
public void setState(State state) {
this.state = state;
notifyObservers("Task " + name + " is now in state: " + state.getClass().getSimpleName());
}
public void create() {
System.out.println("Task " + name + " created.");
setState(new PendingState());
}
public void execute() {
state.handle(this);
}
public void cancel() {
state.handle(this);
}
}
// 用户类
class User implements Observer {
private String name;
public User(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + " received notification: " + message);
}
}
// 监控系统类
class MonitoringSystem implements Observer {
@Override
public void update(String message) {
System.out.println("Monitoring system received notification: " + message);
}
}