命令模式实现文件的创建和删除

运行截图

在这里插入图片描述

代码

项目结构
在这里插入图片描述

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;
	}
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汪程序猿

就当请我吃顿饭

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值