Java composition mode (composite mode)

Source: Internet
Author: User

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 composite

First 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 there is a rule, that is, in the interface to define a to access and manage the composite group of objects (or parts component).

The following code is defined as an abstract class, generally as far as possible with the interface interface.

 Public Abstract classequipment{PrivateString name;//Internet Pricing    Public Abstract DoubleNetprice ();//Discounted price    Public Abstract DoubleDiscountprice ();//Adding part methods    Public BooleanAdd (equipment Equipment) {return false; } //Remove Part method    Public BooleanRemove (equipment Equipment) {return false; } //note here, here is a part method for accessing the Assembly class.     PublicIterator iter () {return NULL; }  PublicEquipment (FinalString 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   ";}  //  definition disk network price is 1  public  double  Netprice () {.;  //  Defines the disk discount price is 0.5 fold.  public  double  Discountprice () { Span style= "color: #0000ff;" >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 classCompositeequipmentextendsequipment{Private intI=0;//define a vector to hold ' son '   PrivateLsit equipment=NewArrayList (); PublicCompositeequipment (String name) {Super(name);}  Public BooleanAdd (equipment equipment) { This. Equipment.add (equipment); return true;}  Public DoubleNetprice () {DoubleNetprice=0.; Iterator ITER=Equipment.iterator ();  for(Iter.hasnext ()) Netprice+=( (equipment) iter.next ()). Netprice (); returnNetprice;}  Public DoubleDiscountprice () {DoubleDiscountprice=0.; Iterator ITER=Equipment.iterator ();  for(Iter.hasnext ()) Discountprice+=( (equipment) iter.next ()). Discountprice (); returnDiscountprice;} //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.    PublicIterator iter () {returnEquipment.iterator (); }    //Overloaded Iterator Method    Public BooleanHasnext () {returni<equipment.size ();} //Overloaded Iterator Method    PublicObject Next () {if(Hasnext ())returnEquipment.elementat (i++); Else       Throw Newnosuchelementexception ();}}

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 classChassisextendscompositeequipment{ PublicChassis (String name) {Super(name);}  Public DoubleNetprice () {return1.+Super. Netprice ();}  Public DoubleDiscountprice () {return.5+Super. Discountprice ();}} Public classCabinetextendscompositeequipment{ PublicCabinet (String name) {Super(name);}  Public DoubleNetprice () {return1.+Super. Netprice ();}  Public DoubleDiscountprice () {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"  =new  Chassis ("PC Chassis"  //  Put the PC chassis in the tower (boxed into the box)  cabinet.add (chassis);  //  load a 10GB hard drive into the PC Chassis (load the hard drive into the enclosure)  Chassis.add ( 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 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 Anatomy

In 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  throws  unauthorizedexception;  Public void  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.

Java composition mode (composite mode)

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.