又叫部分總體模式,這個模式在咱們的生活中也常用,好比說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