首页 > 代码库 > java23中设计模式之组合模式

java23中设计模式之组合模式

技术分享

技术分享

技术分享

 

技术分享
package com.bjsxt.composite;

/**
 * 抽象组件
 * @author Administrator
 *
 */
public interface Component {
    void operation();
}

//叶子组件
interface Leaf extends Component {
}
//容器组件
interface Composite extends Component {
    void add(Component c);
    void remove(Component c);
    Component getChild(int index);
}
component 抽象组件
技术分享
package com.bjsxt.composite;

import java.util.ArrayList;
import java.util.List;

//抽象构建
public interface AbstractFile {
    void killVirus();  //杀毒
}


class ImageFile implements AbstractFile {
    private String name;
    
    public ImageFile(String name) {
        super();
        this.name = name;
    }

    @Override
    public void killVirus() {
        System.out.println("---图像文件:"+name+",进行查杀!");
    }
    
}
class TextFile implements AbstractFile {
    private String name;
    
    public TextFile(String name) {
        super();
        this.name = name;
    }
    
    @Override
    public void killVirus() {
        System.out.println("---文本文件:"+name+",进行查杀!");
    }
}
class VideoFile implements AbstractFile {
    private String name;
    
    public VideoFile(String name) {
        super();
        this.name = name;
    }
    
    @Override
    public void killVirus() {
        System.out.println("---视频文件:"+name+",进行查杀!");
    }
}

class Folder implements AbstractFile {
    private String name;
    //定义容器,用来存放本容器构建下的子节点
    private List<AbstractFile> list = new ArrayList<AbstractFile>();
    
    public Folder(String name) {
        super();
        this.name = name;
    }

    public void add(AbstractFile file){
        list.add(file);
    }
    public void remove(AbstractFile file){
        list.remove(file);
    }
    public AbstractFile getChild(int index){
        return list.get(index);
    }

    @Override
    public void killVirus() {
        System.out.println("---文件夹:"+name+",进行查杀");
        
        for (AbstractFile file : list) {
            file.killVirus();
        }
        
    }
    
}
AbstractFile  例子
技术分享
package com.bjsxt.composite;

public class Client {
    public static void main(String[] args) {
        AbstractFile f2,f3,f4,f5;
        Folder f1 = new Folder("我的收藏");
        
        f2 = new ImageFile("老高的大头像.jpg");
        f3 = new TextFile("Hello.txt");
        f1.add(f2);
        f1.add(f3);
        
        Folder f11 = new Folder("电影");
        f4 = new VideoFile("笑傲江湖.avi");
        f5 = new VideoFile("神雕侠侣.avi");
        f11.add(f4);
        f11.add(f5);
        f1.add(f11);
        
        
//        f2.killVirus();
        
        f1.killVirus();
        
        
    }
}
Client 测试类

 

java23中设计模式之组合模式