The synthetic mode of Java design pattern

Source: Internet
Author: User

Compositing modeThe composition mode expresses the part and the whole relation by the tree structure, which is the structure pattern of the object. The composition mode is to manage the combined objects, so the relevant management methods of the object are given in a certain location, such as add (), remove (), etc. the management of objects in the composition mode has two scenarios. 1. Security method: This method only allows the tree members to have an object management method. 2. Transparent way: This way only allows the tree branches and leaves have the object management method, but the leaf object management method has no practical significance.A. UMLtwo. ComponentAbstract artifacts: Common behavior interfaces of abstract composite objects leaf component: Leaf object, no subordinate sub-object Branch widget: Branch object, Branch object can contain one or more other branches or leaf objectsthree. code example: I take a supermarket shopping as an example(a), Safe Mode 1.Abstract Items(Abstract artifacts)
Package com.eekq.structure.composite.security;/* * Abstract widget, item * */public interface IRes {    /** shopping bill, schematic business method    */ public void pay ();


2.Single Item(Leaf component)
Package Com.eekq.structure.composite.security;public class Singleresimpl implements IRes {    /** Item name */    Private String name;    /** Price */    private float money;    Public Singleresimpl (String name, float money) {        this.name = name;        This.money = money;    }    public void Pay () {        System.out.println ("Purchased an item [" +getname () + "], the price is [" + Getmoney () + "] yuan");    }    public float Getmoney () {        //TODO auto-Generate method stub        Returnthis.money;    }    Public String GetName () {        //TODO auto-Generate Method stub        return this.name;    }      /** rewrite equals*/public    boolean equals (Object obj) {        Singleresimpl res = (singleresimpl) obj;            Return Res.getname (). Equals (GetName ()) && Res.getmoney () ==getmoney ();}    }


3. Multiple Items (branch components)
Package Com.eekq.structure.composite.security;import Java.util.iterator;import java.util.vector;/* * Management of multiple items * */    public class Multiresimpl implements IRes {/** Shopping cart */private vector car = new vector ();     private static float totle = 0.0f;        public void Pay () {if (!car.isempty ()) {System.out.println ("name price \ n");        Shopping ();        System.out.println ("\ n Total Price:" + totle + "Yuan"); }else{System.out.println ("Hello, you did not buy any items, do not pay the bill!")               "); }} public void Shopping () {if (car! = NULL | |!car.isempty ()) {Iterator it = Car.iterator            ();            Singleresimpl res = null;                Object temp = null;//Temporary object while (It.hasnext ()) {temp = It.next ();                if (temp instanceof Multiresimpl) {((Multiresimpl) temp). Shopping ();                    } else {res = (Singleresimpl) temp; Synchronized (this) {TOtle + = Res.getmoney ();                 } System.out.println (Res.getname () + "" + Res.getmoney () + "Yuan");    }}}}/** Add New item */public void addres (IRes res) {Car.add (res);    /** put back the item */public void Removeres (IRes res) {car.remove (res);  } }


4. Cashier's Bill
Package Com.eekq.structure.composite.security;public class Main {/** * @paramargs */public static void Main (string[] args)        {/** Buy an ice cream * */IRes singleres = new Singleresimpl ("Ice Cream", 1.5f);         /** Bill */Singleres.pay ();                      /** Fast New Year, I pushed a shopping cart, buy more things * * IRes allres = Multiresimpl ();        /** Food bought on the first floor * * IRes one = new Multiresimpl (); ((Multiresimpl) allres). Addres (one);//Put things on the first floor in the shopping cart/** because it is a combination of safe mode, it is not transparent enough, can only clear down the transformation, and then added to the shopping cart */((Multiresim        PL) one). Addres (New Singleresimpl ("Wang Wang", 28.5f));        ((Multiresimpl) one). Addres (New Singleresimpl ("Candy", 38.0f));         ((Multiresimpl) one). Addres (New Singleresimpl ("Cola", 8.5f));        /** on the second floor to buy clothes and socks */IRes two = new Multiresimpl ();         ((Multiresimpl) allres). Addres (two);//Put the contents of the second floor in the shopping cart ((Multiresimpl) II). Addres (New Singleresimpl ("clothes", 130.5f));               (Multiresimpl). Addres (New Singleresimpl ("socks", 10f)); /** second Floor bought a watch, I put in Bao*/IRes Bao = new Multiresimpl ();               ((Multiresimpl) two). Addres (Bao);//small shopping bag in the second floor shopping cart ((multiresimpl) Bao). Addres (New Singleresimpl ("Watch", 100f));        /** back to the first floor and bought apples and pears */(Multiresimpl one). Addres (New Singleresimpl ("Apple", 10.0f)); ((Multiresimpl) one). Addres (New Singleresimpl ("Pear", 3.0f))/** I retired the coke before I paid for it, because there was a home. */((MULTIRESIMPL) one). Removeres (        New Singleresimpl ("Cola", 8.5f));    /** on the cashier at a time to pay for all items in the shopping cart * * Allres.pay (); }}


5. Running Results purchased an item [ice cream], the price is [1.5] yuanname Price28.5 YuanCandy 38.0 YuanApple 10.0 YuanPear 3.0 Yuanclothes 130.5 YuanSocks 10.0 YuanWatches 100.0 USDTotal Price: $320.0(ii), transparent mannerthe difference between a transparent and a secure approach is that of an abstract component, which uses a unified interface in a transparent manner. 1. Abstract Artifacts
Package com.eekq.structure.composite.clarity; /* Abstract Widget, item * */public interface IRes {    /** shopping bill, schematic commercial method */public    void Pay ();     /** Add New Item *    /public void addres (IRes res);     /** put back the item *    /public void Removeres (IRes res);}


2.Single Item(Leaf component)
Package com.eekq.structure.composite.security; public class Singleresimpl implements IRes {     /** Item name */    private String name;     /** Price */    private float money;     Public Singleresimpl (String name, float money) {        this.name = name;        This.money = money;    }     public void Pay () {        System.out.println ("Purchased an item [" +getname () + "], the price is [" + Getmoney () + "] yuan");    }     public float Getmoney () {        //TODO auto-Generate Method stub        return this.money;    }     Public String GetName () {        //TODO auto-Generate Method stub        return this.name;    }       /** rewrite equals*/public    boolean equals (Object obj) {        Singleresimpl res = (singleresimpl) obj;            Return Res.getname (). Equals (GetName ()) && Res.getmoney () ==getmoney ();    }


3. Multiple Items (branch components)same as Safe Mode code!4. Cashier's Bill  
Package Com.eekq.structure.composite.clarity;public class Main {/** * @paramargs */public static void Main (        String[] args) {/** buy an ice cream * */IRes singleres = new Singleresimpl ("Ice Cream", 1.5f);        /** Bill */Singleres.pay ();         /** Fast New Year, I pushed a shopping cart, buy more things * * IRes allres = Multiresimpl ();        /** Food bought on the first floor * * IRes one = new Multiresimpl ();        Allres.addres (one);//The first floor of the things in the shopping cart/** because it is a transparent way of the combination mode, so the direct call is the */one.addres (new Singleresimpl ("Wang Wang", 28.5f));        One.addres (New Singleresimpl ("Candy", 38.0f));         One.addres (New Singleresimpl ("Cola", 8.5f));        /** on the second floor to buy clothes and socks */IRes two = new Multiresimpl ();        Allres.addres (two);//The second floor of the things installed in the shopping cart two.addres (new Singleresimpl ("clothes", 130.5f));        Two.addres (New Singleresimpl ("socks", 10f));        /** second Floor bought a watch, I put in Bao */IRes bao = new Multiresimpl ();        Two.addres (bao);//Shopping small package on the second floor shopping cart bao.addres ("watch", 100f);  /** back to the first floor, and bought apples and pears * *      One.addres (New Singleresimpl ("Apple", 10.0f));        One.addres (New Singleresimpl ("Pear", 3.0f));        /** before the bill, I put the coke back, because there are still there * * * * one.removeres (new Singleresimpl ("Cola", 8.5f));    /** on the cashier at a time to pay for all items in the shopping cart * * Allres.pay (); }}


5. Running Results the same results as Safe mode! Four. SummaryThe composition mode is the structure mode of the object, which demonstrates the composition mode above. In future projects, if you encounter a combination of objects, it also conforms to the tree structure. This pattern can be considered. This mode describes the security and transparency methods. Security: Abstract components only provide a common method of leaves and branches, do not provide a unique management of the branches and other methods (add (), remove ()). The benefit is security, the user does not use the Add () management method on the leaves, the disadvantage is not transparent enough, the user must know whether the current object is a leaf or a branch (downward transformation). Transparent: All methods (including add (), remove ()) that satisfy the branch are provided on the abstract component, and the benefit is that the user can arbitrarily execute the object's add () and remove () Management objects. The disadvantage is that if the user executes the management mode (add (), remove ()) on the leaves, there is no error during the compilation period, but the execution time will be error, so it is not easy to find out where the errors are.
If the above content does not understand, recommended blog address: http://lavasoft.blog.51cto.com/62575/90824/

the following data source:Steven John Metsker and William C. Wake Java Design Pattern (second edition) fifth Chapter content:for everyone's reference and study!












Copyright NOTICE: Welcome reprint, Hope in your reprint at the same time, add the original address, thank you with

The synthetic mode of Java design pattern

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.