Java Design Pattern Series (ix) combined mode
Combines objects into a tree structure to represent a "partial-whole" hierarchy. The combined mode makes the user consistent with the use of a single object.
First, the combination mode structure
-
Component: Abstract component objects, which declare interfaces for objects in a composition, allow clients to access and manage the entire object structure through this interface, which provides a default implementation for defined functions.
-
Leaf: Leaf node object, which defines and implements the behavior of the leaf object, no longer contains other child node objects.
-
Composite: Grouping objects typically stores subcomponents, defines the behavior of those components that contain subcomponents, and implements the operations related to subcomponents defined in the component interface.
-
Client: A client that operates a component object within a composite structure through a component interface.
Combination Mode Reference Implementation
(1) First look at the definition of the Component object, the sample code is as follows:
/*** Abstract component objects, declaring interfaces for objects in a composition, implementing default behavior of Interfaces */ Public Abstract classComponent {/** schematic method, sub-component object may have functional methods * / Public Abstract void someoperation();/** Adding a Component object to a composite object * / Public void AddChild(Component Child) {//default implementation, throw exception, because the leaf object does not have this function, or the sub-component does not implement this function Throw NewUnsupportedoperationexception ("Object does not support this feature"); }/** Removing a Component object from a composite object * / Public void RemoveChild(Component Child) {//default implementation, throw exception, because the leaf object does not have this function, or the sub-component does not implement this function Throw NewUnsupportedoperationexception ("Object does not support this feature"); }/** Returns the Component object corresponding to an index * / PublicComponentGetChildren(intIndex) {//default implementation, throw exception, because the leaf object does not have this function, or the sub-component does not implement this function Throw NewUnsupportedoperationexception ("Object does not support this feature"); }}
(2) Next look at the definition of the composite object, the sample code is as follows:
/*** Group objects, usually need to store sub-objects, define the part behavior with subassemblies,* and implements the operations related to subassemblies defined in the component */ Public classCompositeextendsComponent {/*** Used to store sub-component objects contained in a composite object */ PrivateList<component> childcomponents =NULL;/** schematic method, usually in the inside need to implement a recursive call * / Public void someoperation() {if(Childcomponents! =NULL){ for(Component c:childcomponents) {//recursive invocation of the corresponding method of the subassemblyC.someoperation(); } } } Public void AddChild(Component Child) {//Delay initialization if(Childcomponents = =NULL) {childcomponents =NewArraylist<component> (); } childcomponents.Add(child); } Public void RemoveChild(Component Child) {if(Childcomponents! =NULL) {childcomponents.Remove(child); } } PublicComponentGetChildren(intIndex) {if(Childcomponents! =NULL){if(index>=0&& index<childcomponents.size()){returnChildcomponents.Get(index); } }return NULL; }}
(3) To see the definition of the leaf object, relatively simple, the example code is as follows:
/** * 叶子对象,叶子对象不再包含其它子对象 */publicclassextends Component { /** 示意方法,叶子对象可能有自己的功能方法 */ publicvoidsomeOperation() { // do something }}
Public classClient { Public Static void Main(string[] args) {//Define multiple Composite objectsComponent root =NewComposite (); Component C1 =NewComposite (); Component C2 =NewComposite ();//define multiple Leaf objectsComponent LEAF1 =New Leaf(); Component leaf2 =New Leaf(); Component LEAF3 =New Leaf();//Groups and object structures that become tree-shapedRoot.AddChild(C1); Root.AddChild(C2); Root.AddChild(LEAF1); C1.AddChild(LEAF2); C2.AddChild(LEAF3);//Manipulate component ObjectsComponent o = root.GetChildren(1); System. out.println(o); }}
Second, parent component reference
(1) Component
Public Abstract classComponent {/*** Record Parent Component Object */ PrivateComponent parent =NULL;/*** Gets the parent Component object of a component * @returnParent Component Object of a component */ PublicComponentgetParent() {returnParent }/*** Set Parent Component object of a component * @param parentParent Component Object of a component */ Public void setParent(Component Parent) { This.Parent= parent; }/*** Returns the Subassembly object for a component * @returnChild component objects for a component */ PublicList<component>GetChildren() {Throw NewUnsupportedoperationexception ("Object does not support this feature"); }/ *-------------------Below is the original definition----------------------* / /*** The name of the output component itself */ Public Abstract void printstruct(String prestr);/*** Adding component objects to a composite object * @param Childcomponent objects that are added to the composition object */ Public void AddChild(Component Child) {//default implementation, throw exception, because the leaf object does not have this function, or the sub-component does not implement this function Throw NewUnsupportedoperationexception ("Object does not support this feature"); }/*** Remove a Component object from a composite object * @param Childthe Component object that was moved out */ Public void RemoveChild(Component Child) {//default implementation, throw exception, because the leaf object does not have this function, or the sub-component does not implement this function Throw NewUnsupportedoperationexception ("Object does not support this feature"); }/*** Returns the component object corresponding to an index * @param indexindex of the Component object to get, index starting from 0 * @returncomponent objects corresponding to indexes */ PublicComponentGetChildren(intIndex) {Throw NewUnsupportedoperationexception ("Object does not support this feature"); }}
(2) Leaf
Public classLeafextendsComponent {/*** Name of the leaf object */ PrivateString name ="";/*** Construction method, the name of the leaf object passed in * @param namethe name of the leaf object */ Public Leaf(String name) { This.name= name; }/*** The structure of the output leaf object, the leaf object has no sub-object, that is, the name of the output leaf object * @param prestrprefix, mainly in accordance with the level of space stitching, to achieve backward indentation */ Public void printstruct(String prestr) {System. out.println(prestr+"-"+name); }}
(3) Composite
Public classCompositeextendscomponent{ Public void AddChild(Component Child) {//Delay initialization if(Childcomponents = =NULL) {childcomponents =NewArraylist<component> (); } childcomponents.Add(child);//Add a reference to the parent componentChild.setParent( This); } Public void RemoveChild(Component Child) {if(Childcomponents! =NULL) {//Check to find the index position of the component to be deleted in the collection intIDX = childcomponents.indexOf(child);if(IDX! =-1) {The parent product category of the deleted item Category object is set to the parent category of the subcategory of the deleted item category. for(Component C:child.GetChildren()){//Deleted Component object is a subcomponent object of this instanceC.setParent( This);//Add the Sub-component object of the deleted item Category object to the current instanceChildcomponents.Add(c); }//really deleteChildcomponents.Remove(IDX); } } } PublicList<component>GetChildren() {returnchildcomponents; }/ *-------------------The following is the original implementation, no change----------------------* / /*** Used to store sub-component objects contained in a composite object */ PrivateList<component> childcomponents =NULL;/*** Name of the combined object */ PrivateString name ="";/*** Construct method to pass in the name of the combined object * @param namethe name of the combined object */ PublicComposite (String name) { This.name= name; }/*** Structure of the output composition object itself * @param prestrprefix, mainly in accordance with the level of space stitching, to achieve backward indentation */ Public void printstruct(String prestr) {//Lose Yourself FirstSystem. out.println(prestr+"+"+ This.name);//If there are sub-components, then output these subcomponent objects if( This.childcomponents!=NULL){//Then add a space to indent a space backwardprestr+=" ";//Output sub-object of the current object for(Component c:childcomponents) {//Recursively output each sub-objectC.printstruct(PRESTR); } } }}
Iii. Summary (1) The nature of the observer pattern
The essence of the composition pattern: unify the Leaf object and the combined object.
The combination pattern treats the leaf object as a special combination object, thus treats the leaf object and the combination object equally, all as the Component object, organically unifies the leaf object and the combination object.
It is because of the unification of the leaf object and the composition object, when the object is built into a tree structure, it is not necessary to make a distinction, anyway, the Component object contains other component objects, so recursively go down, it makes the operation of the tree structure simple, regardless of object type, unified operation.
(2) When to choose Observer mode
-
If you want to represent the part of the object-the whole hierarchy, you can choose the combination mode, unify the whole and part of the operation, make the hierarchy implementation more simple, from the external to use this hierarchy is simple.
-
If you want to use all the objects in a composite structure uniformly, you can choose the combination mode, which is the main function provided by the composite mode.
(3) Pros and cons of observer patterns
-
Defines a class hierarchy that contains Basic objects and composite objects
In combinatorial mode, the basic objects can be combined into more complex objects, and composite objects can be combined into more complex objects, which can be combined recursively, thus constituting a unified class hierarchy of composite objects.
-
Unify object and leaf objects together
In the combined mode, the leaf object can be treated as a special combination object, defining a uniform parent class for them, thus unifying the behavior of the combined object and the leaf object.
-
Simplifies client invocation
The combined pattern combines objects and leaf objects together so that clients do not need to differentiate them when they use them, and customers do not care what type of objects they use, which greatly simplifies the use of the client.
-
Easier to scale
Since the client is unified in the face of component, the newly defined composite or leaf subclasses can easily work with existing structures, and clients do not need to change to add new component classes
-
Difficult to restrict component types in a composition
The easy addition of new components also poses some problems, such as the difficulty of restricting the types of components in a composition. This is when the component type needs to be detected, so that we cannot rely on the compile-time type constraints to complete and must be dynamically detected during runtime.
Record a little bit every day. Content may not be important, but habits are important!
Java Design Pattern Series (ix) combined mode