当前位置: 首页 > 后端技术 > Java

无性能瓶颈的无限级菜单树应该这样设计

时间:2023-04-01 22:48:17 Java

本文摘自《设计模式就该这样学》1使用透明组合模式实现课程目录结构以在线课程为例,我们设计了一个课程关系结构。比如我们有Java入门课程、人工智能课程、Java设计模式、源码分析、软技能等,而Java设计模式、源码分析、软技能属于Java架构师系列课程包,以及每门课程的定价是不同的。.但是,无论这些课程如何组合,它们都有一些共性,就是整体与部分的关系,可以采用组合模式进行设计。首先创建一个顶层抽象组件CourseComponent类。/***由汤姆创建。*/publicabstractclassCourseComponent{publicvoidaddChild(CourseComponentcatalogComponent){thrownewUnsupportedOperationException("不支持添加操作");}publicvoidremoveChild(CourseComponentcatalogComponent){thrownewUnsupportedOperationException("不支持删除操作支持");}publicStringgetName(CourseComponentcatalogComponent){thrownewUnsupportedOperationException("GetNameoperationisnotsupported");}publicdoublegetPrice(CourseComponentcatalogComponent){thrownewUnsupportedOperationException("不支持获取价格操作");}publicvoidprint(){thrownewUnsupportedOperationException("不支持打印操作");}}把所有可能的方法定义到这个顶层抽象组件,但是不写任何逻辑处理代码,而是直接抛出异常。说到这里,可能有朋友会有疑惑,为什么不用抽象方法呢?因为使用了抽象方法,必须要实现它的子类,这样就体现不出各个子类的细微差别。所以子类继承这个抽象类后,只需要重写不同的方法来覆盖父类的方法即可。然后分别创建课程Course类和课程包CoursePackage类。创建课程类的代码如下。/***由汤姆创建。*/publicclassCourseextendsCourseComponent{privateStringname;私人双重价格;publicCourse(Stringname,doubleprice){this.name=name;这个。价格=价格;}@OverridepublicStringgetName(CourseComponentcatalogComponent){returnthis.name;}@OverridepublicdoublegetPrice(CourseComponentcatalogComponent){returnthis.price;}@Overridepublicvoidprint(){System.out.println(name+"(¥"+price+"元)");}}创建CoursePackage类的代码如下。/***由汤姆创建。*/publicclassCoursePackageextendsCourseComponent{privateListitems=newArrayList();私有字符串名称;私人整数级别;publicCoursePackage(Stringname,Integerlevel){this.name=name;this.level=水平;}@OverridepublicvoidaddChild(CourseComponentcatalogComponent){items.add(catalogComponent);}@OverridepublicStringgetName(CourseComponentcatalogComponent){returnthis.name;}@OverridepublicvoidremoveChild(CourseComponentcatalogComponent){items.remove(catalogComponent);}@Overridepublicvoidprint(){System.out.println(this.name);for(CourseComponentcatalogComponent:items){//控制显示格式if(this.level!=null){for(inti=0;idirs;私人整数级别;publicFolder(Stringname,Integerlevel){super(name);等级;this.dirs=newArrayList();}@Overridepublicvoidshow(){System.out.println(this.name);for(Directorydir:this.dirs){//控制显示格式if(this.level!=null){for(inti=0;i