关于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),违反了设计模式的依赖倒置准则。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理