• [译]Java 设计模式之组合


    (文章翻译自Java Design Pattern: Composite)

    组合模式相对来说是比较简单的,但是它在很多设计中被用到,比如SWT、Eclipse工作空间等等。它创建了一个可以通过唯一的方法访问的继承树。

    类图

    composite-design-pattern

    下面的代码实现了下面树的结构

    Composite-design-pattern-2

    Java 代码

    import java.util.List;
    import java.util.ArrayList;
     
    //Component
    interface Component {
        public void show();
    }
     
    //Composite
    class Composite implements Component {
     
        private List<Component> childComponents = new ArrayList<Component>();
     
        public void add(Component component) {
        	childComponents.add(component);
        }
     
        public void remove(Component component) {
        	childComponents.remove(component);
        }
     
    	@Override
    	public void show() {
    		for (Component component : childComponents) {
            	component.show();
            }
    	}
    }
     
    //leaf
    class Leaf implements Component {
    	String name;
    	public Leaf(String s){
    		name = s;
    	}
        public void show() {
            System.out.println(name);
        }
    }
     
     
    public class CompositeTest {
     
        public static void main(String[] args) {
            Leaf leaf1 = new Leaf("1");
            Leaf leaf2 = new Leaf("2");
            Leaf leaf3 = new Leaf("3");
            Leaf leaf4 = new Leaf("4");
            Leaf leaf5 = new Leaf("5");
     
            Composite composite1 = new Composite();
            composite1.add(leaf1);
            composite1.add(leaf2);
     
            Composite composite2 = new Composite();        
            composite2.add(leaf3);
            composite2.add(leaf4);
            composite2.add(leaf5);
     
            composite1.add(composite2);
            composite1.show();
        }
    }
    
  • 相关阅读:
    Spring Boot配置过滤器的两种方式
    Redis工具类封装RedisUtils
    Android_开机动画
    Android_OTA升级
    QT_学习笔记
    松翰单片机_SN8F570310——ADC
    全志_基于dts设备树驱动开发
    松翰单片机_SN8F570310
    松翰单片机_SN8F570310——GPIO
    松翰单片机_SN8F570310——COM & OPA
  • 原文地址:https://www.cnblogs.com/zhangminghui/p/4214715.html
Copyright © 2020-2023  润新知