龙空技术网

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

计算机视觉教程 546

前言:

此时大家对“java树形菜单栏实现”大约比较关切,同学们都想要分析一些“java树形菜单栏实现”的相关资讯。那么小编也在网络上网罗了一些对于“java树形菜单栏实现””的相关内容,希望小伙伴们能喜欢,小伙伴们快快来了解一下吧!

本文节选自《设计模式就该这样学》

1 使用透明组合模式实现课程目录结构

以一门网络课程为例,我们设计一个课程的关系结构。比如,我们有Java入门课程、人工智能课程、Java设计模式、源码分析、软技能等,而Java设计模式、源码分析、软技能又属于Java架构师系列课程包,每个课程的定价都不一样。但是,这些课程不论怎么组合,都有一些共性,而且是整体和部分的关系,可以用组合模式来设计。首先创建一个顶层的抽象组件CourseComponent类。

/** * Created by Tom. */public abstract class CourseComponent {    public void addChild(CourseComponent catalogComponent){        throw new UnsupportedOperationException("不支持添加操作");    }    public void removeChild(CourseComponent catalogComponent){        throw new UnsupportedOperationException("不支持删除操作");    }    public String getName(CourseComponent catalogComponent){        throw new UnsupportedOperationException("不支持获取名称操作");    }    public double getPrice(CourseComponent catalogComponent){        throw new UnsupportedOperationException("不支持获取价格操作");    }    public void print(){        throw new UnsupportedOperationException("不支持打印操作");    }}

把所有可能用到的方法都定义到这个顶层的抽象组件中,但是不写任何逻辑处理的代码,而是直接抛异常。这里,有些小伙伴会有疑惑,为什么不用抽象方法?因为用了抽象方法,其子类就必须实现,这样便体现不出各子类的细微差异。所以子类继承此抽象类后,只需要重写有差异的方法覆盖父类的方法即可。 然后分别创建课程Course类和课程包CoursePackage类。创建Course类的代码如下。

/** * Created by Tom. */public class Course extends CourseComponent {    private String name;    private double price;    public Course(String name, double price) {        this.name = name;        this.price = price;    }    @Override    public String getName(CourseComponent catalogComponent) {        return this.name;    }    @Override    public double getPrice(CourseComponent catalogComponent) {        return this.price;    }    @Override    public void print() {        System.out.println(name + " (¥" + price + "元)");    }}

创建CoursePackage类的代码如下。

/** * Created by Tom. */public class CoursePackage extends CourseComponent {    private List<CourseComponent> items = new ArrayList<CourseComponent>();    private String name;    private Integer level;    public CoursePackage(String name, Integer level) {        this.name = name;        this.level = level;    }    @Override    public void addChild(CourseComponent catalogComponent) {        items.add(catalogComponent);    }    @Override    public String getName(CourseComponent catalogComponent) {        return this.name;    }    @Override    public void removeChild(CourseComponent catalogComponent) {        items.remove(catalogComponent);    }    @Override    public void print() {        System.out.println(this.name);        for(CourseComponent catalogComponent : items){            //控制显示格式            if(this.level != null){                for(int  i = 0; i < this.level; i ++){                    //打印空格控制格式                    System.out.print("  ");                }                for(int  i = 0; i < this.level; i ++){                    //每一行开始打印一个+号                    if(i == 0){ System.out.print("+"); }                    System.out.print("-");                }            }            //打印标题            catalogComponent.print();        }    }}

最后编写客户端测试代码。

public static void main(String[] args) {        System.out.println("============透明组合模式===========");        CourseComponent javaBase = new Course("Java入门课程",8280);        CourseComponent ai = new Course("人工智能",5000);        CourseComponent packageCourse = new CoursePackage("Java架构师课程",2);        CourseComponent design = new Course("Java设计模式",1500);        CourseComponent source = new Course("源码分析",2000);        CourseComponent softSkill = new Course("软技能",3000);        packageCourse.addChild(design);        packageCourse.addChild(source);        packageCourse.addChild(softSkill);        CourseComponent catalog = new CoursePackage("课程主目录",1);        catalog.addChild(javaBase);        catalog.addChild(ai);        catalog.addChild(packageCourse);        catalog.print();}

运行结果如下图所示。

透明组合模式把所有公共方法都定义在 Component 中,这样客户端就不需要区分操作对象是叶子节点还是树枝节点;但是,叶子节点会继承一些它不需要(管理子类操作的方法)的方法,这与设计模式的接口隔离原则相违背。

2 使用安全组合模式实现无限级文件系统

再举一个程序员更熟悉的例子。对于程序员来说,电脑是每天都要接触的。电脑的文件系统其实就是一个典型的树形结构,目录包含文件夹和文件,文件夹里面又可以包含文件夹和文件。下面用代码来实现一个目录系统。 文件系统有两个大的层次:文件夹和文件。其中,文件夹能容纳其他层次,为树枝节点;文件是最小单位,为叶子节点。由于目录系统层次较少,且树枝节点(文件夹)结构相对稳定,而文件其实可以有很多类型,所以我们选择使用安全组合模式来实现目录系统,可以避免为叶子节点类型(文件)引入冗余方法。首先创建顶层的抽象组件Directory类。

public abstract class Directory {    protected String name;    public Directory(String name) {        this.name = name;    }    public abstract void show();}

然后分别创建File类和Folder类。创建File类的代码如下。

public class File extends Directory {    public File(String name) {        super(name);    }    @Override    public void show() {        System.out.println(this.name);    }}

创建Folder类的代码如下。

import java.util.ArrayList;import java.util.List;public class Folder extends Directory {    private List<Directory> dirs;    private Integer level;    public Folder(String name,Integer level) {        super(name);        this.level = level;        this.dirs = new ArrayList<Directory>();    }    @Override    public void show() {        System.out.println(this.name);        for (Directory dir : this.dirs) {            //控制显示格式            if(this.level != null){                for(int  i = 0; i < this.level; i ++){                    //打印空格控制格式                    System.out.print("  ");                }                for(int  i = 0; i < this.level; i ++){                    //每一行开始打印一个+号                    if(i == 0){ System.out.print("+"); }                    System.out.print("-");                }            }            //打印名称            dir.show();        }    }    public boolean add(Directory dir) {        return this.dirs.add(dir);    }    public boolean remove(Directory dir) {        return this.dirs.remove(dir);    }    public Directory get(int index) {        return this.dirs.get(index);    }    public void list(){        for (Directory dir : this.dirs) {            System.out.println(dir.name);        }    }}

注意,Folder类不仅覆盖了顶层的show()方法,还增加了list()方法。 最后编写客户端测试代码。

    public static void main(String[] args) {        System.out.println("============安全组合模式===========");        File qq = new File("QQ.exe");        File wx = new File("微信.exe");        Folder office = new Folder("办公软件",2);        File word = new File("Word.exe");        File ppt = new File("PowerPoint.exe");        File excel = new File("Excel.exe");        office.add(word);        office.add(ppt);        office.add(excel);        Folder wps = new Folder("金山软件",3);        wps.add(new File("WPS.exe"));        office.add(wps);        Folder root = new Folder("根目录",1);        root.add(qq);        root.add(wx);        root.add(office);        System.out.println("----------show()方法效果-----------");        root.show();        System.out.println("----------list()方法效果-----------");        root.list();}

运行结果如下图所示。

安全组合模式的好处是接口定义职责清晰,符合设计模式的单一职责原则和接口隔离原则;缺点是客户需要区分树枝节点和叶子节点,这样才能正确处理各个层次的操作,客户端无法依赖抽象接口(Component),违背了设计模式的依赖倒置原则。

【推荐】Tom弹架构:收藏本文,相当于收藏一本“设计模式”的书

本文为“Tom弹架构”原创,转载请注明出处。技术在于分享,我分享我快乐!

如果本文对您有帮助,欢迎关注和点赞;如果您有任何建议也可留言评论或私信,您的支持是我坚持创作的动力。私信回复"666"或关注微信公众号『 Tom弹架构 』可获取更多技术干货!

标签: #java树形菜单栏实现