Design Pattern learning in Android --- 1. combination pattern Learning

Source: Internet
Author: User

The Java blog was not updated, busy, and even the address was forgotten. Now I am determined to pick it up again. While learning Android, you can review Java basics. Now I understand that busy is just an excuse. The real reason is that I am too lazy. I am sure I can squeeze out the time to study and summarize it. At least I will write one or two study summaries every weekend. I am determined to stick to it. Well, cheer for yourself.

-------------------------------------------------------------------

The application of the combination mode in Android is everywhere, that is, the use of the view and view group classes. In Android UI design, almost all widgets and layout classes depend on these two classes.

Consider an application:

Product Category tree

Clothing

Men's wear: shirt suit

Women's clothes: skirts

You do not need to use the combination mode:

Consider clothing as the root node. men's wear and women's clothing are tree branches and shirts are leaf nodes. Both the root node and the branches node can contain leaf nodes, so they are considered as a combination class.


Leaf node definition:

package com.light.com;public class Leaf {private String name = "";public Leaf() {}public Leaf(String name) {this.name = name;}@Overridepublic String toString() {return name;}}

Definition of combination classes:

Package com.light.com; import Java. util. arraylist; import Java. util. list; public class composite {private list <composite> composites = new arraylist <composite> (); Private list <leaf> leafs = new arraylist <leaf> (); private string name = ""; Public composite () {} public composite (string name) {This. name = Name;} // Add branches public void addcomposite (composite childcomposite) {composites. add (childcomposite);} // Add the leaf public void addleaf (leaf) {Leafs. add (leaf) ;}@ overridepublic string tostring () {stringbuffer sb = new stringbuffer ("+"); sb. append (this. name + ""); For (composite C: composites) {sb. append (C. tostring ();} sb. append (""); For (leaf L: leafs) {sb. append (L. tostring () + "");} return sb. tostring ();}}

Client:

Package com.light.com; public class client {public static void main (string [] ARGs) {composite root = new composite ("clothing"); composite male = new composite ("men's wear "); composite female = new composite ("Women's Wear"); leaf shirt = new leaf ("shirt"); leaf Jack = new leaf ("jacket "); leaf dress = new leaf ("skirt"); leaf coat = new leaf ("set"); root. addcomposite (male); root. addcomposite (female); male. addleaf (shirt); male. addleaf (Jack); female. addleaf (dress); female. addleaf (COAT); system. out. println (Root );}}

Output result:

+ Clothing

+ Men's wear-shirt-jacket

+ Women's Wear-skirts-Suits


Question:

The combination object and leaf object need to be treated differently. When the number of leaf nodes and branches increases, the program becomes more complex and the scalability is not strong.

Introduce the Combination Mode

Solution:

Define an abstract class. It can represent both leaf objects and composite objects.


Abstract class:

Package com.light.com; public abstract class component {public abstract void dosomething (); Public void addchild (Component component) {// throwing an exception by default, the leaf object does not have this function. Throw new unsupportedoperationexception ("this function is not supported");} public void removechild (Component component) {// The default implementation throws an exception, the leaf object does not have this function. Throw new unsupportedoperationexception ("this function is not supported");} public component getchildren (INT index) {// The default implementation throws an exception, the leaf object does not have this function. Throw new unsupportedoperationexception ("this function is not supported ");}}

Component class:

Package com.light.com; import Java. util. arraylist; import Java. util. list; public class composite extends component {private list <component> components = NULL; private string name; Public composite () {} public composite (string name) {This. name = Name ;}@ overridepublic void dosomething () {// print your own name system. out. println ("+" + this. name); If (components! = NULL) {system. out. print (""); For (component C: Components) {// recursive C. dosomething (); system. out. print ("");} system. out. println () ;}@ overridepublic void addchild (Component component) {If (components = NULL) {components = new arraylist <component> ();} components. add (Component) ;}@ overridepublic void removechild (Component component) {If (components! = NULL) {components. Remove (Component) ;}@ overridepublic component getchildren (INT index) {If (components! = NULL) {If (index >=0 & index <components. Size () {components. Get (INDEX) ;}} return NULL ;}}

Leaf type:

Package com.light.com; public class leaf extends component {private string name = ""; Public leaf () {} public leaf (string name) {This. name = Name ;}@ overridepublic void dosomething () {// print your own name system. out. print ("-" + this. name );}}

Client:

Package com.light.com; public class client {public static void main (string [] ARGs) {component root = new composite ("clothing"); component male = new composite ("men's wear "); component female = new composite ("Women's Wear"); component shirt = new leaf ("shirt"); component Jack = new leaf ("jacket "); component dress = new leaf ("skirt"); component coat = new leaf ("set"); root. addchild (male); root. addchild (female); male. addchild (shirt); male. addchild (Jack); female. addchild (dress); female. addchild (COAT); root. dosomething ();}}

Output result:

+ Clothing

+ Men's wear-shirt-jacket

+ Women's Wear-skirts-Suits


Advantages:

The client will not distinguish whether the operation is a combination object or a leaf object, but operate component objects in a unified manner. Added transparency

Disadvantages:

The client may call useless methods in the leaf node to throw an exception. Security is compromised.


Consider two issues:

1. if you delete a product category. If this category does not have a subcategory, delete it directly. However, if a sub-category exists, you need to delete its sub-classes, and you need to move its sub-categories up to a layer.

2. if goods are refined and sorted out, move the subcategories under category A to category B, and move them together with their subcategories.

Solution:

When a child component object is added to a composite object, the reference of the parent component is set for the child component object. This allows you to reset the reference of the parent component when deleting or moving the child component object. Put these implementations into the abstract class

Improved abstract class:

Package com.light.com; import Java. util. list; public abstract class component {// record parent Component Object private component parent; public component getparent () {return parent;} public void setparent (Component parent) {This. parent = parent;} public list <component> getchildren () {// The default implementation throws an exception. The leaf object does not have this function. Throw new unsupportedoperationexception ("this function is not supported ");} public abstract void dosomething (); Public void addchild (Component component) {// The default implementation throws an exception. The leaf object does not have this function throw new unsupportedoperationexception ("this function is not supported ");} public void removechild (Component component) {// The default implementation throws an exception. The leaf object does not have this function throw new unsupportedoperationexception ("this function is not supported");} public component getchildren (INT index) {// by default, an exception is thrown. The leaf object does not have this function. Throw new unsupportedoperationexception ("this function is not supported ");}}

Improved component classes:

Package com.light.com; import Java. util. arraylist; import Java. util. list; public class composite extends component {private list <component> components = NULL; private string name; Public composite () {} public composite (string name) {This. name = Name ;}@ overridepublic list <component> getchildren () {return components ;}@ overridepublic void dosomething () {// print your name system. out. println ("+" + this. name); If (compone ETS! = NULL) {system. out. print (""); For (component C: Components) {// recursive C. dosomething ();} system. out. println () ;}@ overridepublic void addchild (Component component) {If (components = NULL) {components = new arraylist <component> ();} components. add (component); // set it as the parent class object component. setparent (this) ;}@ overridepublic void removechild (Component component) {If (components! = NULL) {// query the index location of the component to be deleted. Int idx = components. indexof (component); // If the sub-component category is deleted, if (idx! =-1) {// set the parent category of the component under the Child component to its original parent category, Liu Bei togu to Zhuge Liang, And Zhuge Liang to Liu Chan's parent class. For (component C: component. getchildren () {C. setparent (this); components. add (c) ;}/// delete it, and Liu Bei hangs components. remove (idx) ;}@overridepublic component getchildren (INT index) {If (components! = NULL) {If (index >=0 & index <components. Size () {components. Get (INDEX) ;}} return NULL ;}}

The leaf category remains unchanged.

Client:

Package com.light.com; public class client {public static void main (string [] ARGs) {component root = new composite ("clothing"); component male = new composite ("men's wear "); component female = new composite ("Women's Wear"); component shirt = new leaf ("shirt"); component Jack = new leaf ("jacket "); component dress = new leaf ("skirt"); component coat = new leaf ("set"); root. addchild (male); root. addchild (female); male. addchild (shirt); male. addchild (Jack); female. addchild (dress); female. addchild (COAT); root. dosomething (); root. removechild (male); root. dosomething ();}}

Output result:

+ Clothing

+ Men's wear-shirt-jacket

+ Women's Wear-skirts-Suits

+ Clothing

+ Women's Wear-skirts-Suits

-Shirt-jacket

---------------------------------------------------

Implementation of combined modes in Android


Reduced transparency and increased security

View class implementation:

Public Class View {// ...... // irrelevant methods are omitted}

Viewgroup class implementation:

public abstract class ViewGroup extends View{    /**     * Adds a child view.      */    public void addView(View child) {        //...    }     public void removeView(View view) {        //...    }     /**     * Returns the view at the specified position in the group.     */    public View getChildAt(int index) {        try {            return mChildren[index];        } catch (IndexOutOfBoundsException ex) {            return null;        }    }     //other methods}
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.