Java設計模式(九):組合模式composite__Java

來源:互聯網
上載者:User



package com.iter.devbox.composite;import java.util.ArrayList;import java.util.List;/** * 抽象構件 * @author Shearer * */public interface AbstractFile {void killVirus();  //殺毒}class ImageFile implements AbstractFile {private String name;public ImageFile(String name) {this.name = name;}@Overridepublic void killVirus() {System.out.println("---影像檔:" + name + "進行查殺。");}}class TextFile implements AbstractFile {private String name;public TextFile(String name) {this.name = name;}@Overridepublic void killVirus() {System.out.println("---文字檔:" + name + "進行查殺。");}}class VideoFile implements AbstractFile {private String name;public VideoFile(String name) {this.name = name;}@Overridepublic void killVirus() {System.out.println("---視頻檔案:" + name + "進行查殺。");}}//檔案夾(介面)interface IFolder extends AbstractFile {void add(AbstractFile f);void remove(AbstractFile f);AbstractFile getChild(int index);}//檔案夾(實作類別)class Folder implements IFolder {private String name;private List<AbstractFile> list = new ArrayList<AbstractFile>();public Folder(String name) {this.name = name;}public void add(AbstractFile f) {list.add(f);}public void remove(AbstractFile f) {list.remove(f);}public AbstractFile getChild(int index) {return list.get(index);}@Overridepublic void killVirus() {System.out.println("---檔案夾:" + name + "進行查殺。");for (AbstractFile file : list) {file.killVirus();}}}package com.iter.devbox.composite;public class Client {public static void main(String[] args) {AbstractFile file1 = new ImageFile("cat.jpg");AbstractFile file2 = new TextFile("readme.txt");AbstractFile file3 = new VideoFile("海賊王01.mp4");IFolder folder = new Folder("檔案夾01");IFolder subFolder = new Folder("檔案夾02");folder.add(file1);folder.add(subFolder);subFolder.add(file2);subFolder.add(file3);folder.killVirus();}}

運行結果:

---檔案夾:檔案夾01進行查殺。
---影像檔:cat.jpg進行查殺。
---檔案夾:檔案夾02進行查殺。
---文字檔:readme.txt進行查殺。
---視頻檔案:海賊王01.mp4進行查殺。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.