Composite组合模式:
简介:
又叫局部整体模式,这个模式在咱们的生存中也常常应用,比如说Java的AWT编写程序,将按钮,方框等等这些组件有程序的组织成一个界面展现进去,或者说在做ppt的时候将一些形态(圆形,三角形)放在一张ppt下面进行展现,又或者说咱们的目录树结构,树形数据结构等等都是一种组合;
模式实例:
在这里,我以组装树形数据来简略展现一下,运行代码便会明确:
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); } } }}
Flyweight享元模式:
简介:
参考:http://c.biancheng.net/view/1371.html
顾名思义就是共享元数据,在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());}
联合Composite的Flyweight享元模式:
简介:
简略的介绍一下,比方将awt当中的button跟其余的组件组合在一起(当作一个元组件放在池中),而后再拿进去应用,大略就能想到这里