[Original-tutorial-serialization] "android big talk Design Patterns"-structural patterns of design patterns Chapter 1: birthday gifts of the Combination Model mm

Source: Internet
Author: User
<Big talk design model> description and copyright notice of this tutorial

Guoshi studio is a technical team dedicated to enterprise-level application development on the Android platform. It is committed to the best Android Application in China.ProgramDevelopment institutions provide the best Android enterprise application development training services.

Official contact information for Enterprise Training and Development Cooperation:

Tel: 18610086859

Email: hiheartfirst@gmail.com

QQ: 1740415547

QQ: 148325348

Guoshi studio is better for you!

L this document references and uses free images and content on the Internet, and is released in a free and open manner, hoping to contribute to the mobile Internet and the smart phone age! This document can be reproduced at will, but cannot be used for profit.

L if you have any questions or suggestions about this document, go to the official blog

Http://www.cnblogs.com/guoshiandroid/ (with the following contact information), we will carefully refer to your suggestions and modify this document as needed to benefit more developers!

L The latest and complete content of "big talk design mode" will be regularly updated on the official blog of guoshi studio. Please visit the blog of guoshi studio.

Http://www.cnblogs.com/guoshiandroid/get more updates.

Combination ModeMmBirthday present 

Combination ModeUse Cases: 

MM has a birthday today. Said to Gg, "Today's my birthday, you want to give me a big gift:-o", "Well, okay, go to the store and pick it for yourself ." "This T-shirt is very beautiful. It's nice to add this dress. That's it. A set of gifts .", "Can you add anything in the package? It's a full package ......", Gg speechless ~~ O (>_<) O
~~

Explanation of the combination mode: 

Composite pattern is one of the constructor design patterns. composite pattern refers to a hierarchy that combines objects into a tree structure to represent "part-whole, the combination mode ensures consistency between the use of a single object and a combination object.
Compose objects into tree
Structures to represent part-whole hierarchies. Composite lets clients treat
Individual objects and compositions of objects uniformly.

Combination ModeUMLFigure:

The role involved in the combination mode is as follows:

Abstract component role (Component): it is the object declaration interface in the combination, and can also implement default behavior for the common interface.

Leaf component role (leaf): indicates that the leaf node object does not have subnodes in the combination, and implements the interface for declaring the role of the abstract component.

Composite: indicates the branch Node object in the combination. It has subnodes and implements the interface for declaring abstract component roles. It stores sub-parts.

The UML diagram of the combination mode is as follows:

 

In-depth analysis of combined modes:

Change customerCodeDecoupling from the complex object container structure is the core idea of the combination mode. After decoupling, the Customer Code will have a dependency relationship with the pure abstract interface, instead of the complex internal implementation structure of the object container, to better cope with changes.

The management method of child objects must be provided in the combination mode. Otherwise, the addition and deletion of child objects cannot be completed, and flexibility and scalability are lost. But is the management method declared in component or in composite? One way is to declare all the methods used to manage subclass objects in component to maximize the component interface. The goal is to make the customer look that there is no difference between leaf and branch at the interface level-transparency. However, leaves do not have child classes. Therefore, some declared methods are not applicable to leaves. This also brings about some security issues. Another method is to declare all methods used to manage subclass objects in composite. In this way, the security of the previous method is avoided, but because the leaves and branches have different interfaces, the transparency is lost. Design Patterns: In this model, we emphasize transparency over security. Empty processing or exception reporting is not required in the first method.

In a specific implementation, the combination mode allows reverse tracing of sub-objects in the parent object. If the parent object requires frequent traversal, you can use the cache technique to improve efficiency.

Combined Mode scenario analysis and code implementation:

In the above use cases, MM's birthday gift can be seen as the root node, a set of big gifts can be seen as the branches component role, a set of big gifts in the T-shirt, skirt and bag is the leaf component role, the UML diagram is as follows:

Create an abstract interface for the gift node:

package COM. diermeng. designpattern. composite;

Import JAVA. util. list;

/*

* gift node abstraction

*/

Public interface GIFT {

// display the gift's branchor role or leaf. role name

Public void display ();

// Add

Public Boolean Add (gift file );

// remove

Public Boolean remove (gift file );

// obtain subnodes

Public List getchildren ();

}

Gift branches:

PackageCom. diermeng. designpattern. Composite. impl;

ImportJava. util. arraylist;

ImportJava. util. List;

 

ImportCom. diermeng. designpattern. Composite. gift;

 

/*

* The branch node of the gift implements the abstract node of the gift.

*/

Public ClassGiftcompositeImplementsGift {

/*

* Name attribute of the gift tree branch node

*/

PrivateString name;

/*

* Subnode of the gift tree branch node

*/

PrivateList <gift> children;

 

PublicGiftcomposite (string name ){

This. Name = Name;

Children =NewArraylist <gift> ();

}

 

 

Public VoidDisplay (){

System.Out. Println (name );

}

 

PublicList <gift>
Getchildren (){

ReturnChildren;

}

 

 

Public BooleanAdd (gift file ){

ReturnChildren. Add (File );

}

 

 

Public BooleanRemove (gift file ){

ReturnChildren. Remove (File );

}

 

 

}

 

Create leaf nodes for gift nodes:

PackageCom. diermeng. designpattern. Composite. impl;

ImportJava. util. List;

 

ImportCom. diermeng. designpattern. Composite. gift;

 

 

Public ClassGiftleafImplementsGift {

PrivateString name;

 

PublicGiftleaf (string name ){

This. Name = Name;

}

 

 

Public VoidDisplay (){

System.Out. Println (name );

}

 

PublicList <gift>
Getchildren (){

Return Null;

}

 

 

Public BooleanAdd (gift file ){

Return False;

}

 

Public BooleanRemove (gift file ){

Return False;

}

 

}

 

Create a test client:

PackageCom. diermeng. designpattern. Composite. client;

ImportJava. util. List;

 

ImportCom. diermeng. designpattern. Composite. gift;

Import
Com. diermeng. designpattern. Composite. impl. giftcomposite;

ImportCom. diermeng. designpattern. Composite. impl. giftleaf;

 

 

Public ClassCompositetest {

Public Static VoidMain (string [] ARGs ){

// Tree branch component Node

Gift =NewGiftcomposite ("big gift ");

// Leaf component Node

Gift shirt =NewGiftleaf ("T-shirt ");

Gift skirt =NewGiftleaf ("skirt ");

Gift bag =NewGiftleaf ("bags ");

 

// Add the leaf node to the branch node

Gift. Add (shirt );

Gift. Add (skirt );

Gift. Add (BAG );

 

// Call the tree traversal method to display the entire tree

Displaytree(Gift, 0 );

 

}

 

Public Static VoidDisplaytree (gift,IntDeep ){

For(IntI = 0; I <deep; I ++ ){

System.Out. Print ("--");

}

// Display your own name

Gift. Display ();

// Obtain the subtree

List <gift> Children = gift. getchildren ();

// Traverse the subtree

For(Gift file: Children ){

If(FileInstanceofGiftleaf ){

For(IntI = 0; I <= deep; I ++ ){

System.Out. Print ("--");

}

File. Display ();

}Else{

Displaytree(File, deep +
1 );

}

}

}

}

The running result is as follows:

Big gift

-- T-shirt

-- Skirt

-- Bags

Advantages and disadvantages of the combination mode:

Advantages:

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.
It is easier to add object components to the composite body.
The client does not have to change the code because it has added a new object component.

Disadvantages:

Although the combination mode can be used to easily add new object components to the combination body, it brings great flexibility, and the client also modifies the code for this purpose. However, if you do not properly control the new object component, it will constitute a very large tree structure, which will lead to excessive memory overhead during traversal.

Introduction to the application of the combination mode:

The combination mode applies to the following situations:

1: used to represent part-Overall Structure

Second, if you want the client to ignore the combined object en and a single object, the client will use all objects in the combined structure in a unified manner.

At the same time, the combination mode has the following points:

The combination mode uses a tree structure to implement ubiquitous object containers, which converts one-to-many relationships into one-to-one relationships so that the customer code can process objects and object containers in a consistent manner, you do not need to worry about processing a single object or a combined object container.

Decoupling customer code from complex object container structures is the core idea of the combination mode. After decoupling, the Customer Code will be dependent on the pure abstract interface, rather than the complex internal implementation structure of the object container, to better cope with changes.

In the combination mode, the methods related to the object container, such as add and remove, are defined in; the component class of the abstract object is defined in the component class that represents the object container, it is a dilemma of transparency and security, which needs to be carefully weighed. We recommend that you have a transparent approach. This may violate the single responsibility principle of object-oriented, but this is a price that must be paid for this special structure.

In a specific implementation, the combination mode allows reverse tracing of sub-objects in the parent object. If the parent object requires frequent traversal, you can use the cache technique to improve efficiency.

Tip:

The combination mode decouples the internal structure of the client program and complex elements, so that the client program can process complex elements like a simple element.

In the entire object tree, If we often get the parent object from the sub-object, especially the objects of the active root node, we can use the cache technique to improve efficiency.

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.