Java/android Design Pattern Learning Note (---) Combination mode

Source: Internet
Author: User

In this article, we introduce the combination pattern (Composite pattern), which is also known as part of the overall pattern (part-whole pattern), one of the structural patterns. The combination mode is simple, it considers a set of similar objects as an object processing, and combines the objects according to a tree structure, and then provides a uniform way to access the corresponding object, ignoring the difference between the object and the object collection. The most typical example is the tree in the data structure, if a node has child nodes, then it is a branch node, if there is no child node, then it is a leaf node, then how to unify the branch node and leaf node as an object processing it? This requires a combination of patterns.
  
Reprint Please specify source: http://blog.csdn.net/self_study/article/details/51761709.
PS: The technology is interested in the same shoe plus group 5,446,459,721 Exchange.

Total catalog of design patterns

Java/android design mode Learning Notes directory

features

  combined mode allows you to combine objects into a tree structure to represent a "whole/part" hierarchy and enable clients to handle individual objects and group objects in a consistent manner.
The combined mode allows us to create the structure of the object in a tree form, which contains the objects of the composition component and the leaf component, and the same operation can be applied to the composite component and the leaf component, in other words, in most cases we can ignore the difference between the combined object and the leaf object. Scenarios used in composite mode:

    • Represents the part of an object-the overall structure level;
    • A scenario in which a part of a module or function can be detached from a whole.

UML class Diagram

  There are two scenarios for combining patterns in practice: Secure combination mode and transparent combination mode.

Secure Combination Mode

Let's take a look at the UML class diagram of the security combination pattern:
  
You can see that there are 4 characters in the combo mode:

    • Component: Abstract root node, which declares interface behavior for objects in a composition, is the abstraction of all nodes. When appropriate, implements the default behavior for all classes of common interfaces. Declares an interface for accessing and managing child nodes of the Component. An interface can be defined in a recursive structure for accessing a parent node and implementing it in the appropriate case;
    • Composite: Increasing the behavior of defining branch nodes, storing sub-nodes, realizing the related operation in Component interface;
    • Leaf: In the combination of the leaf node object, leaf nodes do not have child nodes, to achieve the Component interface of all operations;
    • Client: Manipulates the combined node object through the Component,composite and Leaf classes.
Thus we can write the common code of the security combination pattern:
Component.class

publicabstractclass Component {    publicabstractvoidoperation();}

Composite.class

 Public  class Composite extends Component{    PrivateArraylist<component> componentlist =NewArraylist<> ();@Override     Public void Operation() {LOG.E ("Shawn","This is composite"+ This+"-------Start"); for(Component component:componentlist)        {component.operation (); } LOG.E ("Shawn","This is composite"+ This+"-------End"); } Public void Add(Component Child)    {Componentlist.add (child); } Public void Remove(Component Child)    {Componentlist.remove (child); } PublicComponentGetchild(intPosition) {returnComponentlist.get (position); }}

Leaf.class

publicclass Leaf extends Component{    @Override    publicvoidoperation() {        Log.e("shawn""this if leaf "this);    }}

Client Test Code:

newnewnew Composite();root.add(leaf1);root.addnew Leaf();branch.add(leaf2);root.operation();break;

The result of the final output:

com. Android. CompositepatternE/shawn:this is compositecom. Android. Compositepattern. Composite. Composite@a37f4d8-------Startcom. Android. CompositepatternE/shawn:this If Leafcom. Android. Compositepattern. Composite. Leaf@1d7d4031com. Android. CompositepatternE/shawn:this is compositecom. Android. Compositepattern. Composite. Composite@ec97316-------Startcom. Android. CompositepatternE/shawn:this If Leafcom. Android. Compositepattern. Composite. Leaf@5dae497com. Android. CompositepatternE/shawn:this is compositecom. Android. Compositepattern. Composite. Composite@ec97316-------Endcom. Android. CompositepatternE/shawn:this is compositecom. Android. Compositepattern. Composite. Composite@a37f4d8-------End

The code is simple, the result is a simple tree structure, but a closer look at the client code, you can find it violates the 6 design pattern principle of dependency inversion principle, the client should not directly rely on the implementation, but should rely on the abstraction, since it is interface-oriented programming, it should be more focus on the design of the interface, This creates a transparent combination of patterns.

Transparent combination mode

Take a look at the transparent combination mode UML class diagram:
  
The difference between the security and the combination mode is that the Composite operation is placed in the Component, which causes the Leaf character to implement all the methods in the Component. Implement the code to make the corresponding changes:
Component.class

publicinterface Component {    void operation();    void add(Component child);    void remove(Component child);    Component getChild(int position);}

Composite.class

 Public  class Composite implements Component{    PrivateArraylist<component> componentlist =NewArraylist<> ();@Override     Public void Operation() {LOG.E ("Shawn","This is composite"+ This+"-------Start"); for(Component component:componentlist)        {component.operation (); } LOG.E ("Shawn","This is composite"+ This+"-------End"); }@Override     Public void Add(Component Child)    {Componentlist.add (child); }@Override     Public void Remove(Component Child)    {Componentlist.remove (child); }@Override     PublicComponentGetchild(intPosition) {returnComponentlist.get (position); }}

Leaf.class

 Public  class Leaf implements Component {    @Override     Public void Operation() {LOG.E ("Shawn","This if Leaf"+ This); }@Override     Public void Add(Component Child) {Throw NewUnsupportedoperationexception ("Leaf can ' t add child"); }@Override     Public void Remove(Component Child) {Throw NewUnsupportedoperationexception ("Leaf can ' t remove child"); }@Override     PublicComponentGetchild(intPosition) {Throw NewUnsupportedoperationexception ("leaf doesn ' t has any child"); }}

Client Test Code

Componentnew Composite();Componentnew Leaf();Componentnew Composite();root.add(leaf1);root.add(branch);Componentnew Leaf();branch.add(leaf2);root.operation();

The result is the same, because all the behavior is defined in the Component class, so the client does not have to rely directly on the implementation of the specific Composite and the Leaf class, and follows the dependency inversion principle-dependency abstraction, without relying on the concrete implementation. But it also violates the principle of single responsibility and interface isolation, so that the Leaf class inherits the methods it should not have, and is not too graceful to throw the unsupportedoperationexception, so that the client can transparently call the corresponding component method, Treats branch nodes and child nodes equally.
In addition, Component is written as a virtual base class, and all the Composite methods are implemented, and by default all exceptions are thrown, only Composite overrides the method of overriding the parent class, and the Leaf class does not need to implement Composite related methods. It is certainly possible to achieve this.

Compare

The security combination model separates the responsibilities from the different interfaces, which makes the design more secure and follows the principle of single responsibility and interface isolation, but also allows the client to rely on the specific implementation, transparent combination mode, the principle of single responsibility and interface isolation principle for transparency, Following the dependency inversion principle, the client directly relies on the Component abstraction to treat the Composite and the leaf equally, that is, whether an element is a branch node or a leaf node, which is transparent to the client.
So this is a typical trade-off case, although we are guided by the principles of design, but we always need to observe the impact of a principle on our design. Sometimes this needs to be analyzed according to the actual case, after all, sometimes 6 design pattern principles in the actual use of the process of conflict, is to let the client each time to check the type or to give the child node should not have the behavior, which depends on the designer's point of view, in general, both of these scenarios are feasible.

Example and source code

There are countless examples of combination patterns in real life, such as menus, folders, and so on. Let's take a look at the very classic implementations of Android as an example. View and ViewGroup should be very familiar with, in fact, they use the combination mode, we first look at the UML class diagram between them:
  
Viewmanager This class is mentioned in the Java/android design mode learning Note (8)-bridging mode, which is also inherited by WindowManager:

/** Interface to let you add and remove a child views to an Activity. To get a instance * of this class, call {@link Android.content.context#getsystemservice (java.lang.String) Context.getsys  Temservice ()}. */ Public  interface viewmanager{    /** * Assign the passed layoutparams to the passed view and add the view to the window. * <p>throws {@link android.view.WindowManager.BadTokenException} for certain programming * errors, such as AddIn     G A second view to a window without removing the first view. * <p>throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a * secondary {@link     Display} and the specified display can ' t be found * (see {@link android.app.Presentation}).     * @param View the view to is added to this window.     * @param params the layoutparams to assign to view. */     Public void AddView(View view, viewgroup.layoutparams params); Public void Updateviewlayout(View view, viewgroup.layoutparams params); Public void Removeview(view view);}

Only three methods are defined for the View operation. The Viewparent class is used to define the responsibilities that a parent view role has, and in Android, it is also the only viewgroup that can be a parent view:

/** * Defines the responsibilities for a class that would be a parent of a view. * This is the API that a view sees whe n it wants to interact with its parent. *  */ Public  interface viewparent {    /** * Called when something have changed which have invalidated the layout of a * child of this view parent.     This would schedule a layout pass of the view * tree. */     Public void Requestlayout();/** * Indicates whether layout is requested on the this view parent. * * @return True if layout was requested, false otherwise */     Public Boolean islayoutrequested(); ....}

It can be noted from the UML class diagram that ViewGroup and view use a secure combination mode instead of a transparent combination mode, no wonder sometimes it is necessary to turn View strong into viewgroup before use.

Summary

Using the combined pattern, we can apply the same actions on the combination and the individual objects, in other words, in most cases we can ignore the differences between the object combination and the individual objects. The combination mode is suitable for the structural design of some interface UI, and the typical example is that Android,ios and Java provide the corresponding UI framework.
Advantages of the combined mode:

    • The combination mode can clearly define the hierarchical complex objects, representing all or part of the object, which makes the high-level modules ignore the differences of the hierarchy and facilitates the control of the whole hierarchy;
    • A high-level module can consistently use a composite structure or a single object, without having to worry about whether it is dealing with a single object or a composite structure, simplifying the code for a high-level module.
    • It is convenient to add new branch members and leaf components in the combined mode, and it is not necessary to make any modification to the existing class library, which conforms to the "open and closed principle";
    • The combination mode provides a flexible solution for the object-oriented implementation of tree structure, which can form complex tree structure through the recursive combination of leaf object and branch object, but the control of tree structure is very simple.
The disadvantage of combinatorial mode is that it is not good to restrict the build types in the branches when adding components, and cannot rely on the type system to impose these constraints, because in most cases they come from the same abstraction layer, which must be implemented by type checking, which is a complex implementation process.

Source Download

Https://github.com/zhaozepeng/Design-Patterns/tree/master/CompositePattern

References

Https://en.wikipedia.org/wiki/Composite_pattern
http://blog.csdn.net/jason0539/article/details/22642281
http://haolloyin.blog.51cto.com/1177454/347308/

Java/android Design Pattern Learning Note (---) Combination mode

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.