Introduction to the combination mode of Java design pattern (composite mode) _java

Source: Internet
Author: User

Composite definition: Organizes objects in a tree structure to achieve a "partial-whole" hierarchy that enables clients to be consistent with the use of individual objects and composite objects.

Composite is easier to understand, think of composite should think of the tree-shaped chart. In a combination, these objects all have a common interface, and when the method of an object of a composition is invoked to execute, Composite will traverse (iterator) the entire tree structure, looking for the same object that contains the method and implement the call execution. Can be used to describe a move hundred.

So the composite mode uses the iterator mode, similar to the chain of responsibility mode.

Composite Benefits:

1. Make the client invocation simple, the client can use the composite structure or a single object, the user does not have to deal with the individual object or the whole composition structure, which simplifies the client code.
2. It is easier to add object parts to the combination body. The client does not have to change the code because of the addition of a new object part.

How to use composite

Define an interface or abstract class first, this is the design pattern common way, the other design pattern has little restriction to the internal definition of the interface, Composite has a stipulation, that is to define an object (or part component) within the interface that is used to access and manage the composite group.

The following code is defined as an abstract class and is generally used as an interface interface.

Copy Code code as follows:

Public abstract class equipment{
private String name;
Network Price
public abstract double Netprice ();
Discounted price
public abstract double Discountprice ();
Add Part method
public boolean Add (equipment equipment) {return false;}
Delete Part method
public boolean remove (equipment equipment) {return false;}
Note here, a part method for accessing the composition class is provided here.
Public iterator Iter () {return null;}
Public equipment (final String name) {This.name=name}
}

The abstract class equipment is the component definition, which represents the objects of the composition class, and the equipment defines several common methods.

Copy Code code as follows:

public class Disk extends equipment{
Public Disk (String name) {super (name);}
Define disk network price is 1
Public double Netprice () {return 1.;}
Definition of disk discount price is 0.5 fold.
Public double Discountprice () {return. 5;}
}

Disk is an object in a combined body, or a part, which is a separate element (primitive).

Another possibility is that a component is also a combination, which means that there is also a ' son ' underneath it, which is usually the case in a tree structure and should be more easily understood. Now let's define this combination:

Copy Code code as follows:

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 here that you provide a way to access the parts of your body in your own assembly.
The reason for this is that 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 equipment, while providing an external access method for the objects inside itself, overloading the iterator,iterator as an interface to the Java collection, is the implementation of the iterator model.

Let's take a look at Compositeequipment's two specific categories: box chassis and box cabinet, the box inside can put a lot of things, such as the bottom plate, power box, hard disk box, etc. can put some small devices, such as HDD floppy disk drive. No doubt both of these are of a combinatorial nature.

Copy Code code as follows:

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 schema.

We can look at the client calling Composote code:

Copy Code code as follows:

Cabinet cabinet=new Cabinet ("Tower");

Chassis Chassis=new Chassis ("PC chassis");
Install PC chassis into tower (boxed in box)
Cabinet.add (chassis);
Install a 10GB hard drive into the PC chassis (load the hard drive into the enclosure)
Chassis.add (New Disk ("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 using iterator to traverse the entire tree structure, looking for the same object that contains the method and implementing the call execution.

Composite is a clever way to embody wisdom, in practical applications, if you encounter a tree structure, we can try to use this pattern.

To forum for example, a version (forum) has a lot of posts (message), these posts have original paste, there is a response to the original paste, is a typical tree structure, then of course can use composite mode, then we go into the jive to see how to achieve.

Jive Anatomy
in Jive, Forumthread is the Forummessages container container (assembly). In other words, Forumthread resembles the compositeequipment in our previous example. Its relationship with messages is as follows:

Copy Code code as follows:

[Thread]
|-[Message]
|-[Message]
|-[Message]
|-[Message]
|-[Message]

We see the following code in Forumthread:
Copy Code code as follows:

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 a way to access parts of your own assembly: Add, Delete, traverse.

Combined 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 must not understand.

Related Article

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.