* if(state==A){
* System.out.println("A的相关方法");
* }else if(state==B){
* System.out.pirntln("B的相关方法");
* }else if(state==C){
* System.out.pritnln("C的相关方法");
* }else if(state==D){
* System.out.println("D的相关方法");
* }……
* }else{
* System.out.pritnln("?的相关方法");
* }
*
发现每进行一次判断就相当于遍历一遍,性能非常底
状态模式的使用 :
*
* 1.对于多种状态下,不同的处理时。
* 2.尽量避免了if else 的繁琐处理
*
* 场景: 画板:
* A.当用户选择了不同的画笔是处理不一样的笔触
具体代码如下:
A.接口
package com.owant.test.state;
/**
*一个状态的模式
*/
public interface State {
public void draw();
}
package com.owant.test.state;
public class Line implements State {
public void draw() {
System.out.println("画一条线");
}
}<span style="font-weight: bold;">
</span>
package com.owant.test.state;
public class Circle implements State {
public void draw() {
System.out.println("画一圆形");
}
}<span style="font-weight: bold;">
</span>
package com.owant.test.state;
public class Empty implements State{
public void draw() {
System.out.println("使用橡皮擦");
}
}<strong>
</strong>
C.载体
package com.owant.test.context;
import java.util.HashMap;
import java.util.Map;
import com.owant.test.state.State;
/**
* 一个实现画画的载体
*/
public class Context {
Map<String, State> toolBar = new HashMap<String, State>();
State toolState;
public void addState(String name, State state) {
toolBar.put(name, state);
}
public void selectSate(String name) {
toolState = toolBar.get(name);
}
public void action(){
toolState.draw();
}
}<strong>
</strong>
D.测试端
package com.owant.test;
import com.owant.test.context.Context;
import com.owant.test.state.Circle;
import com.owant.test.state.Empty;
import com.owant.test.state.Line;
/**
*
* @author owant
*
* 在对于一个状态有相应的动作的程序中,如果状态有多种,一般我们的做法是:
* if(state==A){
* System.out.println("A的相关方法");
* }else if(state==B){
* System.out.pirntln("B的相关方法");
* }else if(state==C){
* System.out.pritnln("C的相关方法");
* }else if(state==D){
* System.out.println("D的相关方法");
* }……
* }else{
* System.out.pritnln("?的相关方法");
* }
*
* 发现每进行一次判断就相当于遍历一遍,性能非常底
*
* 状态模式的使用
*
* 1.对于多种状态下,不同的处理时。
* 2.尽量避免了if else 的繁琐处理
*
* 场景: 画板:
* A.当用户选择了不同的画笔是处理不一样的笔触
*/
public class Client {
public static void main(String[] args) {
Context tool = new Context();
tool.addState("line", new Line());
tool.addState("circle", new Circle());
tool.addState("empty", new Empty());
tool.selectSate("line");
tool.action();
tool.selectSate("circle");
tool.action();
tool.selectSate("empty");
tool.action();
tool.selectSate("circle");
tool.action();
}
}<strong>
</strong>
参考资料: 《研磨设计模式》 《修炼java开发技术:在框架中体验开发模式和算法之美》
欢迎加入QQ群交流:程序设计思想 243134093