又叫部分总体模式,这个模式在咱们的生活中也常用,好比说Java的AWT编写程序,将按钮,方框等等这些组件有顺序的组织成一个界面展现出来,或者说在作ppt的时候将一些形状(圆形,三角形)放在一张ppt上面进行展现,又或者说咱们的目录树结构,树形数据结构等等都是一种组合;html
在这里,我以组装树形数据来简单展现一下,运行代码便会明白:java
abstract class Node{ abstract public void p(); } class LeafNode extends Node { String content; public LeafNode(String content){this.content = content;} @Override public void p() { System.out.println(content); } } class BranchNode extends Node{ List<Node> nodes = new ArrayList<>(); String name; public BranchNode(String name) { this.name = name; } @Override public void p() { System.out.println(name); } public void add(Node n) { nodes.add(n); } } public class Main { public static void main(String[] args) { BranchNode root = new BranchNode("root"); BranchNode chapter1 = new BranchNode("chapter1"); BranchNode chapter2 = new BranchNode("chapter2"); Node c11 = new LeafNode("c11"); Node c12 = new LeafNode("c12"); BranchNode b21 = new BranchNode("section21"); Node c211 = new LeafNode("c211"); Node c212 = new LeafNode("c212"); root.add(chapter1); root.add(chapter2); chapter1.add(c11); chapter1.add(c12); chapter2.add(b21); b21.add(c211); b21.add(c212); tree(root,0); } static void tree(Node b,int depth){ for (int i = 0; i<depth; i++){ System.out.print("--"); } b.p(); if(b instanceof BranchNode){ for(Node n:((BranchNode) b).nodes){ tree(n,depth+1); } } } }
参考:http://c.biancheng.net/view/1371.htmlnode
顾名思义就是共享元数据,在java当中,体现最明显的就是String,String变量引用的常量,若是常量池当中已经存在便不会重复建立数据结构
public static void main(String[] args) { String s1 = "abc"; String s2 = "abc"; String s3 = new String("abc"); String s4 = new String("abc"); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s3 == s4); System.out.println(s3.intern() == s1); System.out.println(s3.intern() == s4.intern()); }
简单的介绍一下,好比将awt当中的button跟其余的组件组合在一块儿(看成一个元组件放在池中),而后再拿出来使用,大概就能想到这里ide