刚看书看到的,关于一个设计模式的状态模式的不错的讲解,是以QQ的登陆.在线,忙碌,离线四个状态的一个说明,代码如下
状态的接口类:
public interface QQState {
void handle(QQ qq);
}
四种不同的状态实现状态接口类
public class LeaveState implements QQState {
public void handle(QQ document) {
//离线状态应该处理代码
document.setState(new LoginingState());
System.out.println("QQ正在登录");
}
}
public class LoginingState implements QQState {
public void handle(QQ document) {
//登录中应该处理代码
document.setState(new LiningState());
System.out.println("QQ已在线");
}
}
public class LiningState implements QQState {
public void handle(QQ document) {
//QQ在线应该处理代码
document.setState(new BusyState());
System.out.println("QQ处在忙碌中");
}
}
public class BusyState implements QQState {
public void handle(QQ document) {
//QQ处在忙碌中应该处理代码
document.setState(new LeaveState());
System.out.println("QQ已离线");
}
}
public class LeaveState implements QQState {
public void handle(QQ document) {
//离线状态应该处理代码
document.setState(new LoginingState());
System.out.println("QQ正在登录");
}
}
public class QQ {
public QQ() {
state = new LeaveState();
}
private QQState state;
public QQState getState(){ return state; }
public void setState(QQState state){ this.state = state; }
public void handle() {
state.handle(this);
}
}
客户端
public class Client {
public static void main(String[] argv) {
QQ qq = new QQ();
qq.handle();
qq.handle();
qq.handle();
qq.handle ();
}
}