美文网首页
结构型模式:09-组合模式

结构型模式:09-组合模式

作者: 综合楼 | 来源:发表于2021-06-13 13:46 被阅读0次
    image.png

    透明组合模式的完整结构

    image.png

    安全组合模式的完整结构

    image.png
    abstract class Component {
        public abstract void add(Component c); //增加成员
    
        public abstract void remove(Component c); //删除成员
    
        public abstract Component getChild(int i); //获取成员
    
        public abstract void operation(); //业务方法
    }
    ----------------------------------------------------------------------
    class Composite extends Component {
        private String name;
        private ArrayList<Component> list = new ArrayList<Component>();
    
        Composite(String name) {
            this.name = name;
        }
    
        @Override
        public void add(Component c) {
            list.add(c);
        }
    
        @Override
        public void remove(Component c) {
            list.remove(c);
        }
    
        @Override
        public Component getChild(int i) {
            return (Component) list.get(i);
        }
    
        @Override
        public void operation() {
            //容器构件具体业务方法的实现
            //递归调用成员构件的业务方法
            for (Object obj : list) {
                ((Component) obj).operation();
            }
        }
    }
    ----------------------------------------------------------------------
    class Leaf extends Component {
        private String name;
    
        public Leaf(String name) {
            this.name = name;
        }
    
        @Override
        public void add(Component c) {
            //异常处理或错误提示
        }
    
        @Override
        public void remove(Component c) {
            //异常处理或错误提示
        }
    
        @Override
        public Component getChild(int i) {
            //异常处理或错误提示
            return null;
        }
    
        @Override
        public void operation() {
            //叶子构件具体业务方法的实现
            System.out.println(name);
        }
    }
    
    class Client {
        public static void main(String args[]) {
            //针对抽象构件编程
            Component file1, file2, file3, file4, file5, folder1, folder2, folder3, folder4;
            folder1 = new Composite("Sunny的资料");
            folder2 = new Composite("图像文件");
            folder3 = new Composite("文本文件");
            folder4 = new Composite("视频文件");
            file1 = new Leaf("小龙女.jpg");
            file2 = new Leaf("张无忌.gif");
            file3 = new Leaf("九阴真经.txt");
            file4 = new Leaf("葵花宝典.doc");
            file5 = new Leaf("笑傲江湖.rmvb");
            folder2.add(file1);
            folder2.add(file2);
            folder3.add(file3);
            folder3.add(file4);
            folder4.add(file5);
            folder1.add(folder2);
            folder1.add(folder3);
            folder1.add(folder4);
            //从“Sunny的资料”节点开始进行杀毒操作
            folder1.operation();
        }
    }
    

    相关文章

      网友评论

          本文标题:结构型模式:09-组合模式

          本文链接:https://www.haomeiwen.com/subject/vqdreltx.html