JAVA design Pattern (20)-combination (composite) mode __java

Source: Internet
Author: User

Definition: group objects into a tree structure to represent a "partial-whole" hierarchy. The composite pattern allows users to have consistency in the use of individual objects and grouped objects.

Type: Object-structured pattern

class Diagram:



structure of the combined pattern

Abstract widget Role (component): Is the object declaration interface in a combination, where appropriate, to implement the default behavior of all classes common interfaces. Declares an interface for accessing and managing the component child parts. This interface can be used to manage all of the child objects.   Optionally, define an interface in a recursive structure that accesses a parent part and implements it where appropriate. Leaf widget Role (leaf): Represents a leaf node object in a composite tree with no child nodes in the leaf node. and defines the behavior of the entity objects in the composition. Branch widget Role (composite): Defines the behavior of those parts that have child parts. The storage child part. Implement actions related to child parts in the component interface. Customer role (client): An object that manipulates a composite part through the component interface.


the combination mode (composite) is implemented in two ways: transparent and secure
Transparency:
Declare all methods used to manage child objects in component, such as the Add () method, the Remove () method, and the Getchild () method, all of which implement the component interface with these methods. This allows the component and subclasses to have a consistent behavior interface, making it unnecessary for the client to distinguish between leaves and tree-like objects.
You can recall that in proxy mode (proxy), the Proxy,realsubject class and the subject interface have a consistent behavior interface, which makes the agent transparent to the client.
Because our composite and leaf have consistent interface behavior, we know that the leaf should not have the add (), remove () and Getchild () methods, because our leaf nodes can no longer add or remove nodes.
Safe Mode: in transparent mode, the component of all the methods used to manage child objects are moved into the composite, and the management method of child objects is implemented in composite, then the leaf has no child object management method. This makes the interface between the composite and the leaf inconsistent, so the client should know the leaves and tree objects exist when called.


composite mode transparent way to implement code

First we define an abstract class componet in which child object operations such as add (), remove () are declared

Abstract class Interface  Component abstract classes
Component {public
	abstract int getchildnum ();
	Public abstract String GetName ();
	Public abstract String GetType ();
	public abstract void Add (Component c);
	public abstract void Remove (Component c);
}


We then define the composite class to inherit from the component, and increase the childlist to save the reference to the Component object, thus establishing the aggregation relationship component to composite (has-a relationship), and implement the abstract method in the component abstract class.

The branch node  Composite class inherits from the Component
class Composite extends Component {
	private String nodename;
	Private list<component> childlist;	Save child node Public

	Composite (String nodename) {
		this.nodename = nodename;
		Childlist = new arraylist<component> ();
	}

	@Override public
	int Getchildnum () {return

		childlist.size ();
	}

	@Override public
	String GetName () {return

		this.nodename;
	}

	@Override public
	String GetType () {return

		"composite";
	}

	@Override public
	Void Add (Component c) {
		childlist.add (c);
	}

	@Override public
	void Remove (Component c) {
		childlist.remove (c);
	}
}

Finally we define the leaf class It also inherits from the component, in which we implement the component defined behavior interface, which makes the composite and the leaf class have uniform interface behavior, but we do not give a specific implementation in the leaf's behavioral method, Because the leaf node does not follow, there is no need to implement add () and remove () behavior.

Leaf node Leaf class also inherits from Component
class Leaf extends Component {
	private String nodename;

	Public Leaf (String nodename) {
		this.nodename = nodename;
	}

	@Override public
	int Getchildnum () {return

		0;
	}

	@Override public
	String GetName () {return

		this.nodename;
	}

	@Override public
	String GetType () {return

		"Leaf";
	}

	@Override public
	Void Add (Component c) {
		System.err.println ("ERROR! Leaf not supported add method! ");
	}

	@Override public
	void Remove (Component c) {
		System.err.println ("ERROR!)". Leaf not supported remove method! ");
	}

Customer Calls

Client Client public
class Compositeclient {

	/**
	 * @param args
	/public static void Main (string[) args) {

		Component root = new Composite ("root");	Root node

		Component composite = new Composite ("composite");	Branch node

		//leaf node
		Component leaf1 = New Leaf ("LEAF1");
		Component leaf2 = new Leaf ("leaf2");

		Composite.add (LEAF2);
		Root.add (LEAF1);
		Root.add (composite);

		String str = "LEAF1 ' s size is" + leaf1.getchildnum ();
		STR + + "\nleaf2 ' s size is" + leaf2.getchildnum ();
		STR + + "\ncomposite ' s size is" + composite.getchildnum ();
		STR + + "\nroot ' s size is" + root.getchildnum ();
		
		System.out.println (str);

	}


Composite applicable scene

Want to represent the part of the object-the overall hierarchy. You want users to ignore the difference between a grouped object and a single object, and the user will use all of the objects in the composite structure uniformly.


several key points of composite combination mode:
The composite model uses the tree structure to realize the Universal object container, which transforms the "One-to-many" relationship into a "one-to-one" relationship, which enables client code to handle objects and object containers consistently, regardless of whether a single object or a combined object container is handled. Decoupling the "client code from the complex object containment structure" is the core idea of the composite pattern, and after decoupling, the client code will be dependent on the pure object interface-rather than the complex internal implementation structure of the object container-and thus more "responsive to change". In composite mode, it is a matter of "transparency" and "security" to define "add and remove and object container-related methods" in "component classes that represent abstract objects" or to define them in "Composite classes for object containers". Dilemma, the need to carefully weigh the structure, which is the price to pay. In the implementation of the composite mode, the object in the parent object can be traced backwards: if the parent object has frequent traversal requirements, caching techniques can be used to improve efficiency


Summary

Combined mode (composite) uses a tree hierarchy to implement object containers, such as: Drawing program Examples we add a variety of shapes to the shape, thus constructing an object chain, transforming the "one-to-many" relationship into a "one-to-one" hierarchical relationship, Enables client code to work with objects and object containers consistently, regardless of whether a single object is being handled or a combined object container. In combination mode (composite), transparent way and safe way of use choice, although the transparent way may violate the object-oriented SRP principle (single responsibility), but the security way does not have the very good encapsulation change, but in actual development we need to weigh the pros and cons according to the concrete situation.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.