Chinaunix首页 | 论坛 | 博客
  • 博客访问: 483133
  • 博文数量: 1496
  • 博客积分: 79800
  • 博客等级: 大将
  • 技术积分: 9940
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-09 13:22
文章分类

全部博文(1496)

文章存档

2011年(1)

2008年(1495)

我的朋友

分类:

2008-09-09 13:31:34

    源自:

    Composite模式:

    将对象组合成树形结构以表示“整体—部分”的层次结构。Composite模式使单个对象和组合对象的使用具有一致性。

    例子:

    view plaincopy to clipboardprint?
    public abstract class MovieClass {

        public String name;
        public ArrayList list;

        public abstract void add(MovieClass component);

        public abstract void remove(MovieClass component);

        public abstract void display();
    }

    public class Program extends MovieClass {

        public Program(String name) {
            this.name = name;
        }

        public void add(MovieClass component) {

            System.out.println("you can't add component to a proagram object");
        }

        public void display() {
            System.out.println("----------" + name);
        }

        public void remove(MovieClass component) {
            System.out.println("you can't remove component to a proagram object");
        }
    }

    public class ConcreteMovieClass extends MovieClass {

        public ConcreteMovieClass(String name) {
            this.name = name;
            list = new ArrayList();
        }

        public void add(MovieClass component) {
            list.add(component);
        }

        public void remove(MovieClass component) {
            if (list.contains(component)) {
                list.remove(component);
            }
        }

        public void display() {
            System.out.println(name);
            for (MovieClass mc : list) {
                mc.display();
            }
        }
    }

    public class Client {

        public static void main(String args[]) {

            Program pro = new Program("大汉天子");
            Program pro2 = new Program("贞观长歌");
            ConcreteMovieClass cmc = new ConcreteMovieClass("电视连续剧");// 一级分类
            cmc.add(pro);
            cmc.add(pro2);
            Program pro3 = new Program("满城尽带黄金甲");
            Program pro4 = new Program("色戒");
            ConcreteMovieClass cmc2 = new ConcreteMovieClass("最新影视");// 一级分类
            cmc2.add(pro3);
            cmc2.add(pro4);
            Program pro5 = new Program("越狱");
            Program pro6 = new Program("英雄");
            ConcreteMovieClass secondCmc = new ConcreteMovieClass("热播美剧");// 二级分类
            secondCmc.add(pro5);
            secondCmc.add(pro6);
            cmc2.add(secondCmc);// 在一级分类(最新影视)下添加二级分类热播美剧
            ConcreteMovieClass root = new ConcreteMovieClass("root");
            root.add(cmc);
            root.add(cmc2);
            root.display();// 显示节目列表
        }
    }

【责编:landy】

--------------------next---------------------

阅读(122) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~