introduce

Composite Pattern, also called partial whole Pattern, is used to treat a group of similar objects as a unit of objects. The composite pattern combines objects based on a tree structure, which is used to represent both part and whole hierarchies. This type of design pattern is a structural pattern that creates a tree structure of groups of objects.

Requirements:

Show how many faculties a school has, how many faculties a college has, and how many faculties a college has.

  • Tsinghua university,
    • School of Computer science
      • Computer Science and Technology
      • Software engineering
    • Information Engineering
      • Communication engineering
      • Information engineering

  1. Create an OrganizationComponent class. This class has an OrganizationComponent object
@Data
@ToString
public abstract class OrganizationComponent {

    /** ** Indicates */
    private String name;

    /** ** Indicates */
    private String des;


    /** * Add method *@param component
     */
    protected void add(OrganizationComponent component){
        throw new UnsupportedOperationException();
    }

    /** * delete *@param component
     */
    protected void remove(OrganizationComponent component){
        throw new UnsupportedOperationException();
    }

    protected abstract void print(a);
    

    public OrganizationComponent(String name, String des) {
        this.name = name;
        this.des = des; }}Copy the code
  1. Create the University school class
public class University extends OrganizationComponent{

    List<OrganizationComponent> list = new ArrayList<>();


    public University(String name, String des) {
        super(name, des);
    }


    @Override
    protected void add(OrganizationComponent component) {
        list.add(component);
    }

    @Override
    protected void remove(OrganizationComponent component) {
        list.remove(component);
    }

    @Override
    protected void print(a) {
        System.out.println("--"+getName()+"-"); list.stream().forEach( component -> { component.print(); }); }}Copy the code
  1. Create a College class
public class College extends OrganizationComponent{
    List<OrganizationComponent> list = new ArrayList<>();


    public College(String name, String des) {
        super(name, des);

    }


    @Override
    protected void add(OrganizationComponent component) {
        list.add(component);
    }

    @Override
    protected void remove(OrganizationComponent component) {
        list.remove(component);
    }

    @Override
    protected void print(a) {
        System.out.println("-- -- -- -- -- -- -- --"+getName()+"-- -- -- -- -- -- -- --"); list.stream().forEach( component -> { component.print(); }); }}Copy the code
  1. Creating a Professional Class
public class Department extends OrganizationComponent{


    public Department(String name, String des) {
        super(name, des);

    }


    @Override
    protected void print(a) {
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- --"+getName()+"-- -- -- -- -- -- -- -- -- -- -- --"); }}Copy the code
  1. Client
public class Client {

    public static void main(String[] args) {
        Build universities from large to small
        University university = new University("Tsinghua university"."985");

        // Create a college
        College college = new College("School of Computer science"."School of Computer science");
        College college2 = new College("School of Information Engineering"."School of Information Engineering");

        // Add professional
        college.add(new Department("Computer Science and Technology"."Computer Science and Technology"));
        college.add(new Department("Network Engineering"."Network Engineering"));

        college2.add(new Department("Communications Engineering"."Communications Engineering"));
        college2.add(new Department("Information Engineering"."Communications Engineering")); university.add(college); university.add(college2); university.print(); }}Copy the code

The composite pattern is used in JDK Maps

  • A Map is an abstract Component, similar to the Component in composite mode.
  • AbstractMap

    is an intermediate Component, but AbstractMap

    is an additional layer between HashMap and Component.
    ,v>
    ,v>
  • Node is a static inner class in a HashMap, similar to Leaf Leaf nodes

Map interface: top-level interface

public interface Map<K.V> {

   
	V put(K key, V value);
	void putAll(Map<? extends K, ? extends V> m); ........................... }Copy the code

AbstractMap abstract class implementation to Map interface: interface implementation, extension

public abstract class AbstractMap<K.V> implements Map<K.V> {


	public V put(K key, V value) {
	        throw new UnsupportedOperationException();
	    }

	public void putAll(Map<? extends K, ? extends V> m) {
	        for(Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); }}Copy the code

HashMap: method implementation

public class HashMap<K.V> extends AbstractMap<K.V>
    implements Map<K.V>, Cloneable.Serializable {

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false.true);
    }


	public void putAll(Map<? extends K, ? extends V> m) {
	        putMapEntries(m, true); }}Copy the code

Inner class Node in the HashMap: It is the Leaf object in the composition mode. It does not combine any child nodes and provides only get and set methods

static class Node<K.V> implements Map.Entry<K.V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey(a)        { return key; }
        public final V getValue(a)      { return value; }
        public final String toString(a) { return key + "=" + value; }

        public final int hashCode(a) {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceofMap.Entry) { Map.Entry<? ,? > e = (Map.Entry<? ,? >)o;if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false; }}Copy the code
  • The HashMap in Map is implemented by applying the composite pattern



Github Demo address: ~ ~ ~ portal ~ ~ ~

Personal blog address: blog.yanxiaolu.cn /