Java中的命令模式是一種設(shè)計(jì)模式,在這種模式下,命令被封裝為對象,從而使它們成為可重用的獨(dú)立單元。這篇文章將介紹如何使用Java命令模式來創(chuàng)建文件和刪除文件。
public interface Command { void execute(); } public class CreateFile implements Command { private String fileName; public CreateFile(String fileName) { this.fileName = fileName; } public void execute() { try { File file = new File(fileName); if (file.createNewFile()) { System.out.println("File created: " + fileName); } else { System.out.println("File already exists: " + fileName); } } catch (IOException e) { System.out.println("Error creating file: " + fileName); e.printStackTrace(); } } } public class DeleteFile implements Command { private String fileName; public DeleteFile(String fileName) { this.fileName = fileName; } public void execute() { File file = new File(fileName); if (file.delete()) { System.out.println("File deleted: " + fileName); } else { System.out.println("Failed to delete file: " + fileName); } } }
在這個(gè)示例代碼中,我們定義了一個(gè)Command接口,包含執(zhí)行命令的execute()方法。然后我們創(chuàng)建了CreateFile和DeleteFile兩個(gè)類,它們都實(shí)現(xiàn)了Command接口。
CreateFile接受一個(gè)文件名作為參數(shù),在execute()方法中會嘗試創(chuàng)建一個(gè)對應(yīng)的文件。如果文件已經(jīng)存在,則會輸出“File already exists”;如果創(chuàng)建成功,則會輸出“File created”。
DeleteFile也接受一個(gè)文件名作為參數(shù),在execute()方法中會嘗試刪除該文件。如果刪除成功,則輸出“File deleted”;否則輸出“Failed to delete file”。
現(xiàn)在,我們可以在程序中使用這些命令了:
public class App { public static void main(String[] args) { Command create = new CreateFile("test.txt"); Command delete = new DeleteFile("test.txt"); create.execute(); delete.execute(); } }
在main()方法中,我們創(chuàng)建了一個(gè)CreateFile對象和一個(gè)DeleteFile對象,并將它們分別賦值給create和delete變量。然后我們調(diào)用它們的execute()方法來執(zhí)行對應(yīng)的命令。
最后,以上代碼將創(chuàng)建一個(gè)名為test.txt的文件,并輸出“File created: test.txt”;然后刪除該文件,并輸出“File deleted: test.txt”。