运行截图
代码
项目结构
package command;
public class TestUse {
public static void main(String args[]) throws Exception{
//接收者
MakeFile makeFile = new MakeFile();
//命令
CommandCreate create = new CommandCreate(makeFile);
CommandDelete delete = new CommandDelete(makeFile);
//请求者
Client client = new Client();
//执行命令
client.setCommand(create).executeCommand("d://test1.txt");
client.setCommand(create).executeCommand("d://test2.txt");
client.setCommand(delete).executeCommand("d://test2.txt");
}
}
package command;
//请求者
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);
}
}
package command;
//命令接口
public interface Command {
void execute(String name) throws Exception;
}
package command;
//新建文件命令
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);
}
}
package command;
//删文件命令
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);
}
}
package command;
import java.io.File;
import java.io.IOException;
//接收者
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;
}
}