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); }} ///:~
退耦:指消除或减轻两个以上物体间在某方面相互影响的方法 Proxy模式最大的用途很显然被用来控制访问“被代理者类”对象的实现。这两种模式很像,因为Proxy模式是一种特殊的State模式,即只有一种State。 他们的相同之处是:他们都由“代理者类”控制“被代理者类”。Proxy模式和State模式不同在于State模式有多个实现,而proxy模式只有一个。Proxy模式被用来控制访问它的实现,State模式允许你动态的改变实现。