java组合模式的结果和适用的场景

发布时间:2021-09-04 11:19:39 作者:chen
来源:亿速云 阅读:105

本篇内容主要讲解“java组合模式的结果和适用的场景”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java组合模式的结果和适用的场景”吧!

组合(Composite)模式的定义:有时又叫作部分-整体模式,它是一种将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系。组合模式使得客户端代码可以一致地处理单个对象和组合对象,无须关心自己处理的是单个对象,还是组合对象,这简化了客户端代码;

模式结构

源码导读

组合模式分为透明模式和安全模式;透明模式是在顶层抽象中声明了所有管理子对象的方法,树叶节点点和树枝节点对于客户端来说没有区别。安全模式是在顶层抽象中只声明叶子和树枝公有的抽象方法,而将对叶子和树枝的管理方法实现到对应的类中,因此客户端就需要区分该节点是树枝还是叶子从而调用对应的方法。

对组合模式来说,List Set等这些集合类属于不那么严格的组合模式。由于没有找到太好的源码,因此我在这里分别对透明模式和安全模式组合说明

透明模式:

public abstract class Component{
    private String name;
    public Component(string name)
    {
        this.name = name;
    }
 
    public abstract boolean Add(Component component);
 
    public abstract boolean Remove(Component component);
 
    public String getName(){
        return name;
    }
}

public class Branch extend Component{
    private List<Component> tree=new ArrayList<>();
    
    public Branch(String name){
        super(name);
    }
    
    public boolean add(Componet component){
        tree.add(component);
        return true;
    }
    
    public boolean Remove(Component component){
        tree.remove(component);
        return true;
    }
}

public class Leaf extend Component{
    
     public Leaf(String name){
        super(name);
    }
     
     public boolean add(Componet component){
        return false;
    }
    
    public boolean Remove(Component component){
        return false;
    }
    
}

安全模式:

public abstract class Component{
    private String name;
    public Component(string name)
    {
        this.name = name;
    }
 
    public String getName(){
        return name;
    }
    
    
}

public class Branch extend Component{
    private List<Component> tree=new ArrayList<>();
    
    public Branch(String name){
        super(name);
    }
    
    public boolean add(Componet component){
        tree.add(component);
        return true;
    }
    
    public boolean Remove(Component component){
        tree.remove(component);
        return true;
    }
    
    public List<Component> getTree(){
        return tree;
    }
}

public class Leaf extend Component{
    
     public Leaf(String name){
        super(name);
    }
    
    
}

组合模式适用的场景为需要表述一个系统(组件)的整体与部分的结构层次的场合;组合模式可对客户端隐藏组合对象和单个对象的不同,以便客户端可以使用用统一的接口使用组合结构中的所有对象,对于该类场合也适用于组合模式

到此,相信大家对“java组合模式的结果和适用的场景”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. redis适用于哪些场景
  2. cdn的概念以及适用场景

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:安装wordpress到虚拟主机的步骤

下一篇:MySQL中的隐藏列的具体查看方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》