Composite (combination) of design patterns)

Source: Internet
Author: User

Composite definition:
The object is organized in a tree structure to form a "part-whole" hierarchy, so that the client can use a single object and a composite object in a consistent manner.

The Composite is easy to understand, and the Composite should think of the tree structure. These objects in the Composite have a common interface. When the method of an object in the Composite is called and executed, Composite traverses the entire tree structure (Iterator, find the object that contains the same method and execute the call. It can be described as a hundred moves.

Therefore, the Composite mode uses the Iterator mode, which is similar to the Chain of Responsibility mode.

Benefits of Composite:
1. make the client simple to call. The client can use a combination structure or a single object in it, and the user does not have to worry about whether to process a single object or the entire combination structure, which simplifies the client code.
2. It is easier to add object parts in the composite body. The client does not have to change the code because it has added new object parts.

How to Use Composite?
First, define an interface or abstract class. This is a general method of design patterns. Other design patterns have few restrictions on Internal interface definitions, but Composite has a rule, that is to define an object (or Component) inside the interface for accessing and managing the Composite combination ).

The following code is defined as an abstract class. Generally, the interface is used whenever possible,

Public abstract class Equipment
{
Private String name;
// Network price
Public abstract double netPrice ();
// Discount price
Public abstract double discountPrice ();
// Add part Method
Public boolean add (Equipment equipment) {return false ;}
// Part deletion method
Public boolean remove (Equipment equipment) {return false ;}
// Note that here, we provide a component method for accessing the Assembly class.
Public Iterator iter () {return null ;}
  
Public Equipment (final String name) {this. name = name ;}
}

The abstract class Equipment is the definition of Component, which represents the objects of the composite class. Equipment defines several common methods.

Public class Disk extends Equipment
{
Public Disk (String name) {super (name );}
// Define the Disk Network price as 1
Public double netPrice () {return 1 .;}
// Defines that the disk discount price is 0.5.
Public double discountPrice () {return. 5 ;}
}

Disk is an object in a combination, or a component, which is a separate element (Primitive ).
Another possibility is that a component is also a combination, that is to say, there is a 'son' under this component. This is a common situation in the tree structure and should be easier to understand. Now we need to define this combination:

Abstract class CompositeEquipment extends Equipment
{
Private int I = 0;
// Define a Vector to store '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 that here we provide a method to access the parts in the body of your group.
// The reason why the above dIsk does not exist is that Disk is a separate (Primitive) element.
Public Iterator iter ()
{
Return equipment. iterator ();
{
// Reload the Iterator Method
Public boolean hasNext () {return I <equipment. size ();}
// Reload the Iterator Method
Public Object next ()
{
If (hasNext ())
Return equipment. elementAt (I ++ );
Else
Throw new NoSuchElementException ();
}
  

}

The above CompositeEquipment inherits Equipment and provides external access methods for the objects in itself. Iterator is a Java Collection interface and is implemented in the Iterator mode. www.2cto.com

Let's take a look at the two types of CompositeEquipment: the disk box Chassis and the box Cabinet. There are many things in the box, such as the baseboard, power box, and hard box. There are some small devices in the disk box, such as hard drive. Undoubtedly, both of them belong to the combination.

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 ();}
}

So far, we have completed the architecture of the entire Composite model.

Let's take a look at the client's code for calling Composote:

Cabinet cabinet = new Cabinet ("Tower ");

Chassis chassis = new Chassis ("PC Chassis ");
// Install PC Chassis into the Tower (bind the disk to the box)
Cabinet. add (chassis );
// Attach a 10 Gb hard disk to PC Chassis (attach the hard disk to the disk box)
Chassis. add (new Disk ("10 GB "));

// Call the netPrice () method;
System. out. println ("netPrice =" + cabinet. netPrice ());
System. out. println ("discountPrice =" + cabinet. discountPrice ());

The method netPrice () or discountPrice () called above, in fact Composite uses Iteratbor to traverse the entire tree structure, find the object that also contains this method and implement the call execution.

Composite is a clever expression of wisdom. in practical applications, If we encounter a tree structure, we can try to use this mode.

Taking the forum as an example, there are many posts in a forum. These posts have original posts and response stickers for the original posts, which is a typical tree structure, of course, you can use the Composite mode, so let's go to Jive to see how it is implemented.

Jive anatomy
In Jive, ForumThread is the container iner of ForumMessages. That is to say, ForumThread is similar to CompositeEquipment in the above example. Its relationship with messages
[Thread]
|-[Message]
|-[Message]
|-[Message]
|-[Message]
|-[Message]

We can 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, the component method used to access the body of the combination is provided: Add Delete traversal.

Based on the analysis of Jive in other models, we have basically understood the framework of the Jive forum system. If you do not understand the design model before, you can directly look at the Jive source code, you cannot understand it.

:)


Author: tbwshc

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.