HeadFirst设计模式_读书笔记_005_命令模式
程序员文章站
2022-05-03 23:26:20
...
命令模式:允许将发出请求的对象和接受并执行这些请求的对象分割开来,即实现请求调用者和请求接受者之间的解耦。定义:将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。
调用命令的是Invoker,执行命令的实际上是Receiver。通过命令模式,将各种动作封装成Command,实现了Invoker和Receiver的彻底解耦。Invoker只管发出命令,Receiver只管执行相应的操作。
public interface Command { public void execute(); }
public class Dog { public void foundBone() { System.out.println("找骨头~~"); } public void bark() { System.out.println("汪汪~~"); } public void sing() { System.out.println("狗狗在唱歌~~"); } }
public class DogBarkCommand implements Command{ private Dog dog; public DogBarkCommand(Dog dog) { this.dog = dog; } @Override public void execute() { dog.bark(); } }
public class DogFoundBoneCommand implements Command { private Dog dog; public DogFoundBoneCommand(Dog dog) { this.dog = dog; } @Override public void execute() { dog.foundBone(); } }
public class DogSingCommand implements Command{ private Dog dog; public DogSingCommand(Dog dog) { this.dog = dog; } @Override public void execute() { this.dog.sing(); } }
public class Invoker { Command command; public void setCommand(Command command) { this.command = command; } public void invoke() { this.command.execute(); } }
public class Test { public static void main(String args[]) { Dog dog = new Dog(); Command barkcommand = new DogBarkCommand(dog); Invoker invoker = new Invoker(); invoker.setCommand(barkcommand); invoker.invoke(); } }
上一篇: 看下下面的地址是用的什么框架呢
下一篇: php如何统计访问次数?