状态模式和策略模式

状态模式

定义状态基类:

public interface State {
	public void run();
	public void sleep();
}

定义两个状态:

public class EnergeticState implements State {
	public void run() {
		System.out.print("跑得快");
	}
	public void sleep() {
		System.out.print("睡不着");
	}
}

public class TiredState implements State {
	public void run() {
		System.out.print("跑不动");
	}
	public void sleep() {
		System.out.print("睡得香");
	}
}

Person类中定义一个状态:

public class Person {
	private State state = new TiredState();
	
	public void setTried(boolean isTired) {
		//提供一个方法修改State对象就可以控制Person的执行逻辑了
		state = isTired ? new TiredState() : new EnergeticState();
	}
	
	public void run(){
		state.run();
	}
	public void sleep(){
		state.sleep();
	}
}

使用:

	Person person = new Person();
	person.setTried(true);					//通过flag来切换状态
	person.run();							//跑不动
	person.sleep();							//睡得香
策略模式:

与状态模式类似,只是不用状态Flag来修改策略,而是注入一个策略,还是用上面的例子:

public class Person {
	private State state = new TiredState();
	
	public void setState(State state) {
		this.state = state;
	}
	
	public void run(){
		state.run();
	}
	public void sleep(){
		state.sleep();
	}
}

使用:

	Person person = new Person();
	person.setState(new TiredState());			//通过注入切换策略
	person.run();								//跑不动
	person.sleep();								//睡得香
总结:

可以用在if else分支过多导致逻辑混乱的情况
缺点是每个状态(策略)都对应一个类,可能导致类型过多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值