Composite definition: Organize objects in a tree-shaped structure to achieve a "partial-overall" hierarchy, making the client consistent with the use of individual objects and composite objects.
Composite is easier to understand, think of composite should think of tree-shaped structure diagram. These objects in the composition have a common interface, and when a method of an object is called to execute, Composite will traverse (Iterator) The entire tree structure, looking for an object that also contains the method and implementing the call execution. Can be used to describe a move hundred.
so the composite mode is used in iterator mode, similar to the chain of responsibility mode.
Composite Benefits:
- Making the client invocation simple, the client can consistently use a composite structure or a single object, and the user does not have to deal with a single object or the entire composition structure, simplifying the client code.
- It is easier to add object parts to the body of a group. The client does not have to change the code because it joins a new object part.
How to use compositefirst define an interface or abstract class, this is the design pattern common way, the other design patterns on the internal definition of the interface is not much, composite has a rule, That is to define an object (or part component) that is used to access and manage the composite group within the interface.
The following code is defined as an abstract class, generally as far as possible with the interface interface. Public abstract class equipment{
private String name;
Internet pricing
public abstract double Netprice ();
Discounted price
public abstract double Discountprice ();
Adding part methods
public boolean Add (equipment equipment) {return false;}
Remove Part method
public boolean remove (equipment equipment) {return false;}
Note Here, here is a part method for accessing the Assembly class.
Public Iterator iter () {return null;}
Public equipment (final String name) {this.name=name;}
}abstract class equipment is the definition of component, which represents the objects of the composition class, and defines several common methods in equipment. public class Disk extends equipment{
Public Disk (String name) {super (name);}
Define disk network price is 1
Public double Netprice () {return 1.;}
Defined disk discount price is 0.5 fold in half.
Public double Discountprice () {return. 5;}
}disk is an object in a group, or a part, which is a separate element (Primitive).
Another possibility is that a component is also a combination, that is, there is a ' son ' under this part, which is usually the case in the tree structure, which should be more easily understood. Now we need to define this composition first:Abstract class Compositeequipment extends equipment{
private int i=0;
Define a vector to hold ' son '
Private lsit equipment=new ArrayList ();
Public compositeequipment (String name) {super (name);}
public boolean Add (equipment equipment) {
This.equipment.add (equipment);
return true;
}
Public double Netprice () {
Double netprice=0.;
Iterator Iter=equipment.iterator ();
For (Iter.hasnext ())
netprice+= ((equipment) iter.next ()). Netprice ();
return netprice;
}
Public double Discountprice () {
Double discountprice=0.;
Iterator Iter=equipment.iterator ();
For (Iter.hasnext ())
discountprice+= ((equipment) iter.next ()). Discountprice ();
return discountprice;
}
Note here that this provides a way to access parts of your own assembly.
The reason that disk is not there is because disk is a separate (Primitive) element.
Public Iterator iter () {
return Equipment.iterator ();
}
Overloaded Iterator method
public Boolean Hasnext () {return i<equipment.size ();}
Overloaded Iterator method
Public Object Next () {
if (Hasnext ())
Return Equipment.elementat (i++);
Else
throw new Nosuchelementexception ();
}
}The above Compositeequipment inherits the equipment, and also provides an external access method for the objects inside, overloading the iterator,iterator is an interface of Java collection, is the implementation of the iterator pattern.
Let's take a look at Compositeequipment's two specific classes: Tray box chassis and box cabinet, the box can put a lot of things, such as the backplane, power box, hard disk box, etc., the box can put some small devices, such as hard disk floppy drive. Undoubtedly these two belong to the combination nature. public class Chassis extends compositeequipment{
Public Chassis (String name) {super (name);}
Public double Netprice () {return 1.+super.netprice ();}
Public double Discountprice () {return. 5+super.discountprice ();}
}
public class Cabinet extends compositeequipment{
Public Cabinet (String name) {super (name);}
Public double Netprice () {return 1.+super.netprice ();}
Public double Discountprice () {return. 5+super.discountprice ();}
}at this point we have completed the architecture of the entire composite model.
we can look at the client call Composote code:Cabinet cabinet=new Cabinet ("Tower");
Chassis chassis=new Chassis ("PC Chassis");
Load the PC chassis into the tower (pack the tray into the box)
Cabinet.add (chassis);
Attach a 10GB hard drive to the PC Chassis (load the hard drive into the enclosure)
Chassis.add ("Ten GB");
Call the Netprice () method;
System.out.println ("netprice=" +cabinet.netprice ());
System.out.println ("discountprice=" +cabinet.discountprice ());the method called above Netprice () or Discountprice (), actually composite uses iterator to traverse the entire tree structure, looking for objects that also contain this method and implementing the call execution.
Composite is a clever model of wisdom, and in practice, if you encounter a tree structure, we can try to use this pattern.
take the forum as an example, there are many posts in a version (message), these posts have the original paste, there is a response to the original sticker, is a typical tree structure, then of course you can use the composite mode, then we enter the jive to see how it is implemented.Jive Anatomyin Jive Forumthread is the Forummessages container container (composition). In other words, Forumthread is similar to the compositeequipment in our previous example. Its relationship to messages is as follows:
[Thread]
|-[message]
|-[message]
|-[message]
|-[message]
|-[message]
we see the following code in Forumthread:Public interface Forumthread {
....
public void AddMessage (Forummessage parentmessage, Forummessage newmessage)
Throws Unauthorizedexception;
public void DeleteMessage (Forummessage message)
Throws Unauthorizedexception;
Public Iterator messages ();
....
}similar to Compositeequipment, provides methods for accessing parts of your own composition: Add, delete, traverse.
In combination with my other models of jive analysis, we have basically understood the framework of the Jive Forum system, if you do not understand the design pattern, and directly to see Jive Source code, you certainly can not read.
Combination mode
Overview
Combines objects into a tree structure to represent a "partial-whole" hierarchy. "Composite makes the user consistent with the use of individual objects and composite objects. "
Applicability
1. You want to represent the part of the object-the overall hierarchy. 2. You want users to ignore the difference between a combined object and a single object, and the user will use all the objects in the composite structure uniformly.
participants
1.Component declares an interface for an object in a group. when appropriate, implements the default behavior for all classes of common interfaces. declares an interface for accessing and managing component subcomponents. Optionally, define an interface in the recursive structure to access a parent part and implement it where appropriate. 2.Leaf represents a leaf node object in a group, and the leaf node has no child nodes. defines the behavior of a node object in a composition. 3.Composite Defines the behavior of those parts that have child parts. stores the child parts. implement operations related to subassemblies in the component interface. 4.Client An object that manipulates a combined part via the component interface.
class Diagram
Example
Component
Public abstract class Employer { private String name; public void SetName (String name) { this.name = name; } Public String GetName () { return this.name; } public abstract void Add (employer employer); public abstract void Delete (employer employer); public List employers; public void Printinfo () { System.out.println (name); } Public List getemployers () { return this.employers; }}
Leaf
public class Programmer extends employer {public Programmer (String name) { setName (name); Employers = null;//Programmer, indicates no subordinate, } public void Add (Employer employer) { } public void Delete (employer Employer) { }}
public class Projectassistant extends employer {public projectassistant (String name) { setName (name); Employers = null;//Project assistant, indicating that there is no subordinate, public void Add (Employer employer) { } public void Delete ( Employer employer) { }}
Composite
public class Projectmanager extends employer {public Projectmanager (String name) { setName (name); Employers = new ArrayList (); } public void Add (Employer employer) { employers.add (employer); } public void Delete (Employer employer) { employers.remove (employer);} }
Client
public class Test {public static void Main (string[] args) { employer PM = new Projectmanager ("Project manager"); Employer PA = new Projectassistant ("Project Assistant"); Employer Programmer1 = new Programmer ("Programmer One"); Employer Programmer2 = new Programmer ("Programmer II"); Pm.add (PA);//Add Project Assistant Pm.add (PROGRAMMER2) for Project Manager,//Add programmer to Project manager List EMS = Pm.getemployers (); for (employer Em:ems) { System.out.println (Em.getname ());}}}
result
Project Assistant Programmer II
Java composition mode (composite mode)