zoukankan      html  css  js  c++  java
  • Java组合模式

    定义:将对象组合成树形结构以表示  部分--整体的层次结构

    组合模式使客户端对单个对象和组合对象保持一致的方式处理

    类型:结构型

    优点:

    1.清楚地定义分层次的复杂对象,表示对象的全部去或部分层次

    2.让客户端忽略了层次的差异,方便对整个层次结构进行控制

    3.简化客户端代码

    4.符合开闭原则

    public abstract class CatalogComponent {
        public void add(CatalogComponent catalogComponent){
            throw new UnsupportedOperationException("不支持添加操作");
        }
        public void remove(CatalogComponent catalogComponent){
            throw new UnsupportedOperationException("不支持删除操作");
        }
        public String getName(CatalogComponent catalogComponent){
            throw new UnsupportedOperationException("不支持获取名称操作");
        }
        public double getPrice(CatalogComponent catalogComponent){
            throw new UnsupportedOperationException("不支持获取价格操作");
        }
        public void print(){
            throw  new UnsupportedOperationException("不支持打印操作");
        }
    }
    

      

    public class Course extends CatalogComponent {
        private  String name;
        private  double price;
    
        public Course(String name, double price) {
            this.name = name;
            this.price = price;
        }
    
        @Override
        public String getName(CatalogComponent catalogComponent) {
            return this.name;
        }
    
        @Override
        public double getPrice(CatalogComponent catalogComponent) {
            return this.price;
    
        }
    
        @Override
        public void print() {
            System.out.println("Course Name:"+name+" price:"+price);
        }
    }
    

      

    public class CourseCatalog extends  CatalogComponent{
        private List<CatalogComponent> items=new ArrayList<CatalogComponent>();
        private  String name;
        private  Integer level;
    
        public CourseCatalog(String name,Integer level) {
            this.name = name;
            this.level=level;
        }
    
        @Override
        public void add(CatalogComponent catalogComponent) {
            items.add(catalogComponent);
        }
    
        @Override
        public void remove(CatalogComponent catalogComponent) {
            items.remove(catalogComponent);
        }
    
        @Override
        public void print() {
            System.out.println(this.name);
            for(CatalogComponent catalogComponent:items){
                if(this.level!=null){
                    for(int i=0;i<this.level;i++){
                        System.out.println("   ");
                    }
                }
                catalogComponent.print();
            }
        }
    }
    

      

  • 相关阅读:
    Windows python 鼠标键盘监控及控制
    python 执行adb shell 命令
    python Windows提示框
    判断function属于函数或方法
    生成不同时间下的LOG
    pyqt5 QCalendar类中常用的方法
    python字符串大小写转换
    configparser 模块的基本方法
    QGridLayout类中常用的方法
    Day049--jQuery的文档操作和事件介绍
  • 原文地址:https://www.cnblogs.com/sunliyuan/p/10635920.html
Copyright © 2011-2022 走看看