企业架构、智能体设计 State模式探讨(笔记心得体会) 2004-03-14 tbase 定义: 状态的切换 我的理解就是State模式可以改变对象的行为。 State模式在实际使用中比较多,适合"状态的切换".因为我们经常会使用If elseif else 进行状态切换, 如果针对状态的这样判断切换反复出现,我们就要联想到是否可以采取State模式了.(节选自“板桥里人 http://www.jdon.com 2002/4/6/ 设计模式之State” 何时使用?) //: state:StateDemo.javaimport junit.framework.*;interface State { void operation1(); void operation2(); void operation3();}class ServiceProvider { private State state; public ServiceProvider(State state) { this.state = state; } public void changeState(State newState) { state = newState; } // Pass method calls to the implementation: public void service1() { state.operation1(); state.operation3(); } public void service2() { state.operation1(); state.operation2(); } public void service3() { state.operation3(); state.operation2(); }}class StateA implements State { public void operation1() { System.out.println("StateA.operation1()"); } public void operation2() { System.out.println("StateA.operation2()"); } public void operation3() { System.out.println("StateA.operation3()"); }}class StateB implements State { public void operation1() { System.out.println("StateB.operation1()"); } public void operation2() { System.out.println("StateB.operation2()"); } public void operation3() { System.out.println("StateB.operation3()"); }}public class StateDemo extends TestCase { static void run(ServiceProvider sp) { sp.service1(); sp.service2(); sp.service3(); } ServiceProvider sp = new ServiceProvider(new StateA()); public void test() { run(sp); // change state .we can change implemention. sp.changeState(new StateB()); run(sp); } public static void main(String args[]) { junit.textui.TestRunner.run(StateDemo.class); }} ///:~ Object decoupling的解释。 退耦:指消除或减轻两个以上物体间在某方面相互影响的方法 Proxy模式最大的用途很显然被用来控制访问“被代理者类”对象的实现。这两种模式很像,因为Proxy模式是一种特殊的State模式,即只有一种State。 他们的相同之处是:他们都由“代理者类”控制“被代理者类”。Proxy模式和State模式不同在于State模式有多个实现,而proxy模式只有一个。Proxy模式被用来控制访问它的实现,State模式允许你动态的改变实现。
banq 2010-01-09 19:55 2010年01月09日 15:55 "zqs1031"的内容状态是否为内存中的状态而不是数据库中存储的状态 在对象设计世界中,是看不到数据库的,是没有数据库概念的。所以,内存中状态或数据库存储的状态其实就是同一个状态,就象你在单位活动工作,然后到床上睡觉冬眠一样,不能说这两个不同形式就是不同的人了。
banq 2010-01-18 10:48 2010年01月17日 19:51 "maying112"的内容状态模式耦合度很大。因为要暴露所有状态子类 状态模式封装的就是状态,不能暴露状态,应该暴露事件。[该贴被banq于2010-01-18 10:48修改过]