Design pattern (ix) combined mode (Composite)-Structural type

Source: Internet
Author: User

Combination Mode composite

The combination mode is also called the synthesis mode , is called the tree pattern , is the partial and the whole relationship uses the tree structure to represent, is the client to the individual object and the combination object's use has the consistency, can see, here the part and the whole is functionally similar, For this kind of similarity, it can usually be implemented in the way of inheritance, according to the principle of object-oriented design, as far as possible to use the combination rather than inheritance, so the composition pattern is also an inheritance of a replacement scheme.

1. Combined mode structure


Schematic diagram of the combined mode implementation
The combination pattern is the representation of the relationship of the part and the whole in a tree-like structure, so that the client can look at the same way that a part of the object and the whole object are grouped together. It is also a replacement for inheritance, using a combination pattern that provides more flexibility than using inheritance, and the flexibility to combine the relationships between child objects and parent objects, making the client's invocation simple and the client consistently using a composite structure or a single object. Users do not have to care whether they are dealing with a single object or the entire composition structure, which Simplified Client Code

2. Composition of the build pattern

The composition pattern is mainly 3 parts: abstract class , leaf class , parent class .
Abstract Component Role (component): This is an abstract role that defines common interfaces and default behavior for participating groups. Can be used to manage all child objects. In a secure synthetic mode, a component role is not a method of defining a managed sub-object, as defined by the tree Component object.
Leaf component Role (leaf): The leaf node object is represented in the composition tree, and the leaf node has no child nodes. and defines the behavior of the entity objects in the composition.
Branch Component Role (Composite): Defines the behavior of those parts that have child parts. Stores the child parts. Implement operations related to subassemblies in the component interface.
Customer role (client): The object that manipulates the combined part through the component interface.

3. Combination Mode effect

(1) A class hierarchy that contains Basic objects and composite objects can be combined into more complex objects, and this combination of objects can be combined so that they continue recursively. In the customer code, you can use a composite object wherever you use the base object.
(2) Simplify customer code customers can consistently use composite structures and individual objects. Usually the user does not know (and does not care) whether the processing is a leaf node or a composite component. This simplifies the customer code, because there is no need to write some functions that are riddled with selection statements in those classes that define the composition.
(3) Make it easier to add new types of components the newly defined composite or leaf subclass automatically works with the existing structure and customer code, and the client program does not need to be changed by the new component class.
(4) to make your design more generalized it is also problematic to add new components, which makes it difficult to limit the components in a composition. Sometimes you want a combination to have only some specific components. When using composite, you cannot rely on the type system to impose these constraints, but must be checked at run time.

4. Implementation Code

Example: Life often used in the subtraction operation, and sometimes to the basic operation of the data after the operation, the following use of the combination of patterns implemented.
Salarycomputer.java

package/**  * @author  作者:ldw E-mail: [email protected] * @version 创建时间:2015年4月25日 上午9:16:12  * 类说明  */publicinterface SalaryComputer {    publicdoublecomputer(double m,double n);}

addition Operation Class Code:
Add.java

package/**  * @author  作者:ldw E-mail: [email protected] * @version 创建时间:2015年4月25日 上午9:16:47  * 类说明  */publicclass Add implements SalaryComputer{    @Override    publicdoublecomputer(doubledouble n) {        return m+n;    }}

Subtraction Class implementation code:
Subtract.java

package/**  * @author  作者:ldw E-mail: [email protected] * @version 创建时间:2015年4月25日 上午9:16:47  * 类说明  */publicclass Subtract implements SalaryComputer{    @Override    publicdoublecomputer(doubledouble n) {        return m-n;    }}

Multiplication Class implementation code:
Multiplication.java

package/**  * @author  作者:ldw E-mail: [email protected] * @version 创建时间:2015年4月25日 上午9:16:47  * 类说明  */publicclass Multiplication implements SalaryComputer{    @Override    publicdoublecomputer(doubledouble n) {        return m*n;    }}

Division class implementation code:
Division.java

package/**  * @author  作者:ldw E-mail: [email protected] * @version 创建时间:2015年4月25日 上午9:16:47  * 类说明  */publicclass Division implements SalaryComputer{    @Override    publicdoublecomputer(doubledouble n) {        return m/n;    }}

combined class operation code :
Composite.java

 PackageCom.devin.composite;ImportJava.util.ArrayList;ImportJava.util.List;/** * @author Author: ldw e-mail: [email protected] * @version created: April 25, 2015 9:18:20 * class description */ Public  class Composite implements salarycomputer {    Privatelist<salarycomputer> list =NewArraylist<salarycomputer> (); Public void Add(Salarycomputer Salarycomputer)    {List.add (salarycomputer); } Public void Remove(Salarycomputer Salarycomputer)    {List.remove (salarycomputer); }@Override     Public Double Computer(DoubleMDoubleN) {DoubleCount =0; for(inti =0; I < list.size ();            i++) {Salarycomputer salarycomputer = (salarycomputer) list.get (i);        count+= Salarycomputer.computer (M, n); } System.out.println ("m="+ M +", n="+ N +"The result of the calculation is"+count);returnCount }}

Client code:
Client.java

package/**  * @author  作者:ldw E-mail: [email protected]  * @version 创建时间:2015年4月25日 上午9:23:46  * 类说明  */publicclass Client {    publicstaticvoidmain(String[] args) {        new Composite();        salaryComputer.add(new Division());        salaryComputer.computer(20005);    }}
5. Test results
m=1000.0,n=5.0 计算后的结果为200.0
6. Combination mode and other related modes

(1) Decorative mode (decorator mode) is often used in conjunction with Composite mode. When decorations and compositions are used together, they usually have a common parent class. The adornment must therefore support the component interface with ADD, remove, and getchild operations.
(2) The enjoy meta mode (Flyweight) mode lets you share components, but no longer refer to their parent parts.
(3) The iterator mode (itertor) can be used to traverse the composite.
(4) The Observer pattern (Visitor) should be localized in operations and behavior that should have been distributed in the composite and L e a F classes.

7. Summary
    • The combined mode decouples the internal structure of the client and complex elements, allowing the client program to handle complex elements as simple elements.
    • If you want to create hierarchies and can treat all the elements in the same way, then the combined pattern is the ideal choice.
the application in practice

JUnit Unit test framework, and so on.

Design pattern (ix) combined mode (Composite)-Structural type

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.