命令模式将请求封装成一个对象,实现了命令发出者和实现者的解耦
先看实现者:
package com.whereta.command;/** * Vincent 创建于 2016/5/4. * 接受者:用于处理具体逻辑 */public abstract class Recevier { protected abstract void doSomething();}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Receiver1 extends Recevier { protected void doSomething() { System.out.println("Receiver1..."); }}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Receiver2 extends Recevier { protected void doSomething() { System.out.println("Receiver2..."); }}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Receiver3 extends Recevier { protected void doSomething() { System.out.println("Receiver3..."); }}
命令对象:
package com.whereta.command;/** * Vincent 创建于 2016/5/4. * 命令类 */public abstract class Command { protected Recevier recevier1=new Receiver1(); protected Recevier recevier2=new Receiver2(); protected Recevier recevier3=new Receiver3(); protected abstract void execute();}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Command1 extends Command { protected void execute() { super.recevier1.doSomething(); }}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Command2 extends Command { protected void execute() { super.recevier2.doSomething(); }}
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Command3 extends Command { protected void execute() { super.recevier3.doSomething(); }}
调用者:
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Invoker { private Command command; public Invoker(Command command) { this.command = command; } public void action(){ command.execute(); }}
测试:
package com.whereta.command;/** * Vincent 创建于 2016/5/4. */public class Main { public static void main(String[] args) { Command command=new Command1(); Invoker invoker=new Invoker(command); invoker.action(); }}
输出:
Receiver1...
从上可以看出:命令类里的具体实现要依赖接受者
策略模式的策略类已经有了具体实现不依靠第三方
个人博客: