一个对象有多种操作,但是我们不希望调用者(请求者)直接使用,我们就额外添加一个对象,然后让调用者通过这个对象来使用那些操作。
比如,我们有一个类可以在磁盘上新建或是删除文件(接收者),但是我们不希望直接提供给别人(请求者)使用,所以我们就为它的各种操作创建对应的命令,下面我们用代码来实现这个需求:
接收者,可以在磁盘删除或新建文件:
//接收者public class MakeFile { //新建文件 public void createFile(String name) throws IOException{ File file = new File(name); file.createNewFile(); } //删除文件 public boolean deleteFile(String name){ File file = new File(name); if(file.exists()&&file.isFile()){ file.delete(); return true; } return false; }}
然后就是执行操作的接口:
//命令接口public intece Command { void execute(String name) throws Exception;}
我们需要创建具体的命令,这里就是2个,新建和删除:
//新建文件命令public class CommandCreate implements Command { MakeFile makeFile; public CommandCreate(MakeFile makeFile) { this.makeFile = makeFile; } @Override public void execute(String name) throws Exception { makeFile.createFile(name); }}//删文件命令public class CommandDelete implements Command{ MakeFile makeFile; public CommandDelete(MakeFile makeFile) { this.makeFile = makeFile; } @Override public void execute(String name) throws Exception { makeFile.deleteFile(name); }}
最后就是请求者了:
//请求者public class Client { Command command; public Client setCommand(Command command){ this.command = command; return this; } public void executeCommand(String name) throws Exception{ if(command==null) throw new Exception("命令不能为空!"); command.execute(name); }}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-33893-14.html
加速了中国造假业的发展