State 模式

模式定义

 

State模式允许一个对象在内部状态改变时它的行为也随着改变,实现其类在运行时的动态修改。

使用范围

 

  • 行为取决于对象的状态
  • 太多的分支语句来区别处理不同状态下的行为

使用方法

 

举例说明

 

Socket网络编程中假设我们定义它有三个状态,Open, Listen和Close。从不同的状态中抽象出一个接口 TcpStatus。该接口定义了网络操作中的三个方法,建立连接,显示当前状态,退出连接。

public interface TcpStatus {
	void establish();
	void exit();
	void acknowledge();
}

再定义TcpStatus的三个状态。注意每个状态下的不同方法定义了不同的行为,该行为是根据当前状态而定的。

public class TcpOpen implements TcpStatus{

	public void acknowledge() {
		System.out.println("tcp connection opened");
	}

	public void exit() {
		System.out.println("Conn Closing");
	}

	public void establish() {
		System.out.println("Conn opened");
	}

}

----------------

public class TcpListen implements TcpStatus{

	public void acknowledge() {
		System.out.println("Conn listening");
	}

	public void establish() {
		System.out.println("Conn opened, can not open again");
	}

	public void exit() {
		System.out.println("Closing");
	}

}

----------------

public class TcpClose implements TcpStatus {

	public void acknowledge() {
		System.out.println("Conn closed");
	}

	public void exit() {
		System.out.println("Conn closed, can not close again.");
	}

	public void establish() {
		System.out.println("Conn opening");
	}

}

建立一个Context,用来管理状态的切换和更新。

public class TcpConnection {
	private TcpStatus status;

	public void open(){
		this.status = new TcpOpen();
		this.status.establish();
		this.status = new TcpListen();
	}
	
	public void close(){
		this.status.exit();
		this.status = new TcpClose();
	}
	public void acknowledge(){
		this.status.acknowledge();
	}

}

客户端方法:

public class StateClient {
	public static void main(String args[]){
		TcpConnection conn = new TcpConnection();
		conn.open();
		conn.acknowledge();
		conn.close();
		conn.acknowledge();
		conn.open();
		conn.close();
		conn.acknowledge();
		conn.close();
	}

}

运行结果:

Conn opened
Conn listening
Closing
Conn closed
Conn opened
Closing
Conn closed
Conn closed, can not close again.

下载示例

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值