Design pattern combination mode (Composite) and code examples Detailed

Defines a combination of mode

  Define combinations of (Composite) mode: sometimes called portion - the whole pattern, which is a mode of the objects into the hierarchy tree that represents - Relations "integral part" of the individual objects and the user composite object has the same accessibility. This type of design pattern belongs structural model, it creates a tree structure of the target group.

  Combinations are represented by polymerization and overall relationship of the individual, the biggest difference between them is the degree of controlled subclasses parent. The parent-child relationship based composition polymerizable stronger than:

  • Polymerization: has-a relationships, parent class contains subclasses, subclasses can exist independently of the parent

  Class ==> Student: classes and students is an aggregation relationship. A class, a student can be no students; conversely, when the dissolution of the class, students still exists; at the same time students can belong to multiple classes (interest classes, extra-curricular classes).

  • Composition: part-of relationship, the child has a parent class, subclass, can not exist in the parent

  Body ⇒ Cell: cell body and is a combination of relationships. But we create a body, the cells will be created; conversely, when we destroy a body, the cells will be destroyed.

Second, the advantages and disadvantages of combined mode

  The main advantage of the combination modes are:

  • So that client code combination pattern can uniformly process a single combined object and objects, without concern for their processing a single object or combination of objects, which simplifies the client code;
  • Body composition easier to add new objects, the client will not be added to the new object and change the source code, to meet the "on-off principle";

  The main disadvantages are:

  • Design more complex, the client needs to spend more time to sort out the hierarchical relationships between classes;
  • It is not easy to limit the container member;
  • New features a method is not easy to increase the inherited member;

Third, to achieve the combined mode

  Structural combination mode is not very complex, its structure and achieve the following analysis.

  Combined mode includes the following major role.

  • Abstract component (Component) role: its main role is as a member of leaves and twigs members declared public interface, and to achieve their default behavior. In combined mode Transparent member also stated in the abstract interface to access and manage subclass; not declare an interface to access and manage the security of formula subclass combination mode management performed by the branch member.
  • Leaf member (Leaf) role: is a leaf node objects in the group, it does not have child nodes that may enable a common interface abstraction component role in the declaration.
  • Branch member (Composite) Role: is a branch node objects in the group, it has child nodes. It implements the interface declared abstract member role, its main role is to store and manage sub-components, typically comprising Add (), Remove (), GetChild () method and the like.

  Transparent combination patterns into the combination modes and security type combination pattern.

  Transparent mode : In this mode, because the abstract component declares all the methods in all sub-categories, so clients do not need the difference between the leaves and twigs target object, the client is transparent. But its disadvantages are: leaf members had no Add (), Remove () and GetChild () method, have to implement them (empty implementation or throw an exception), it will bring some security issues. The structure shown in Figure:

              

  If you want to access the set c0 = {leaf1, {leaf2, leaf3}} elements, which corresponds to the tree as shown:

                   

  Which code is implemented as follows:

public  class CompositePattern
{
    public static void main(String[] args)
    {
        Component c0=new Composite();
        Component c1=new Composite();
        Component leaf1=new Leaf("1");
        Component leaf2=new Leaf("2");
        Component leaf3=new Leaf("3");
        c0.add(leaf1);
        c0.add(c1);
        c1.add(leaf2);
        c1.add(leaf3);
        c0.operation();
    }
}

// abstract component 
interface the Component
{
    void add(Component c);
    void remove(Component c);
    Component getChild(int i);
    void operation();
}

// leaf member 
class Leaf the implements the Component
{
    private String name;
    public Leaf(String name)
    {
        this.name=name;
    }
    public void add(Component c){ }
    public void remove(Component c){ }
    public Component getChild(int i)
    {
        return null;
    }
    public void operation()
    {
        System.out.println ( "leaves" + name + ": is accessed!" );
    }
}

// branch member 
class Composite the implements the Component
{
    private ArrayList<Component> children=new ArrayList<Component>();
    public void add(Component c)
    {
        children.add(c);
    }
    public void remove(Component c)
    {
        children.remove(c);
    }
    public Component getChild(int i)
    {
        return children.get(i);
    }
    
    public void operation()
    {
        for(Object obj:children)
        {
            ((Component)obj).operation();
        }
    }
}

  Output:

Leaves 1: is accessed!
Leaves 2: The access!
Leaves 3: is accessed!

  Security mode : In this mode, the method of managing sub-component is moved to a branch member, abstract component and leaves no management member sub-objects, thus avoiding the security issues on a way, but because the leaves and branch has a different interface, when the client calls the objects to be aware of the existence of leaves and twigs of the object, so the loss of transparency. The structure shown in Figure:

              

  Which code is implemented as follows:

public  class CompositeSafePattern
{
    public static void main(String[] args)
    {
        CompositeSafe c0=new CompositeSafe();
        CompositeSafe c1=new CompositeSafe();
        ComponentSafe leaf1=new LeafSafe("1");
        ComponentSafe leaf2=new LeafSafe("2");
        ComponentSafe leaf3=new LeafSafe("3");
        c0.add(leaf1);
        c0.add(c1);
        c1.add(leaf2);
        c1.add(leaf3);
        c0.operation();
    }
}

// abstract component 
interface ComponentSafe
{
    void operation();
}

// leaf member 
class LeafSafe the implements ComponentSafe
{
    private String name;
    public LeafSafe(String name)
    {
        this.name=name;
    }
    public void operation()
    {
        System.out.println ( "leaves" + name + ": is accessed!" );
    }
}

// branch member 
class CompositeSafe the implements ComponentSafe
{
    private ArrayList<ComponentSafe> children=new ArrayList<ComponentSafe>();
    public void add(ComponentSafe c)
    {
        children.add(c);
    }
    public void remove(ComponentSafe c)
    {
        children.remove(c);
    }
    public ComponentSafe getChild(int i)
    {
        return children.get(i);
    }

    public void operation()
    {
        for(Object obj:children)
        {
            ((ComponentSafe)obj).operation();
        }
    }
}

Fourth, the practical application of the combination mode

  Note: If Mr. Lee to Shaoguan "e-day street corner" daily necessities store shopping with a small red bag pack 2 installed Wuyuan specialty (unit price 7.9 yuan), a Wuyuan map (unit price of 9.9 yuan); with a white small bag installed two packages Shaoguan incense by (unit price of 68 yuan) and 3 packets Shaoguan tea (Unit 180 yuan); with an in bag for holding the front of a small red bag and a Jingdezhen porcelain (Unit 380 yuan); with 1 a big bag for holding the bag in front of, and one pair of small white pouch lining sports shoes (198 yuan Unit).

  Finally, the contents of "big bags" in are: {1 pair Ning sports shoes (Unit 198 yuan), small white pouch {2 packet Shaoguan mushrooms (Unit 68 yuan), 3 packet Shaoguan tea (Unit 180 yuan)}, in the bag {1 Jingdezhen porcelain (380 yuan Unit), a small red bag package Wuyuan {2 specialty (7.9 yuan Unit), a map Wuyuan (Unit 9.9 yuan)}}}, now requires programming displayed on the big bag of Li All product information and calculate the total price to be paid.

  Code is implemented as follows (written secure mode):

/**
 * Note: If Mr. Lee to Shaoguan "e-day street corner" daily necessities store shopping with a small red bag pack 2 installed Wuyuan specialty (unit price 7.9 yuan), a Wuyuan map (unit price of 9.9 yuan);
 * With a small white bag for holding two packages Shaoguan incense by (unit price of 68 yuan) and 3 packets Shaoguan tea (Unit 180 yuan); with an in bag for holding the front of a small red bag and a Jingdezhen porcelain (Unit 380 yuan);
 * With a big bag for holding the bag in front of, and one pair of small white pouch lining sports shoes (198 yuan Unit).
 * 
 * Content last "big bags" in are: {1 pair Ning sports shoes (Unit 198 yuan), 
* Small white pouch {2 packet Shaoguan mushrooms (Unit 68 yuan), 3 packet Shaoguan tea (Unit 180 yuan)}, In the bag 1 * {Jingdezhen porcelain (380 yuan Unit),
* 2 {small red bag package Wuyuan specialty (7.9 yuan Unit), a map Wuyuan (Unit 9.9 yuan)}}}, * Lee now required to display programming information on the total price of all the goods in big bags and calculate to be paid.
*/ public class CompositeApplying { public static void main(String[] args) { float s = 0; Bags BigBag, mediumBag, smallRedBag, smallWhiteBag; Goods sp; The Big- Bag = new new Bags ( "big bag" ); mediumBag = new new Bags ( "in the bag" ); smallRedBag = new new Bags ( "Red small bag" ); smallWhiteBag = new new Bags ( "White small bag" ); SP = new new Goods ( "Wuyuan specialty", 2, 7.9f ); smallRedBag.add(sp); SP = new new Goods ( "Wuyuan map",. 1, 9.9f ); smallRedBag.add(sp); SP = new new Goods ( "Shaoguan mushroom", 2, 68 ); smallWhiteBag.add(sp); SP = new new Goods ( "Shaoguan tea", 3, 180 ); smallWhiteBag.add(sp); SP = new new Goods ( "Jingdezhen porcelain", 1, 380 ); mediumBag.add(sp); mediumBag.add(smallRedBag); SP = new new Goods ( "Li Ning sneakers", 1, 198 ); BigBag.add(sp); BigBag.add(smallWhiteBag); BigBag.add(mediumBag); System.out.println ( "You buy the product are:" ); BigBag.show(); s = BigBag.calculation(); System.out.println ( "total price to be paid is:" + s + "dollars" ); } } @ Abstract component: Item interface Articles { public a float Calculation (); // calculate public void Show (); } // leaf member: Goods class Goods the implements Articles { Private String name; // name Private int Quantity; // Number Private a float unitPrice,; // Price public Goods(String name, int quantity, float unitPrice) { this.name = name; this.quantity = quantity; this.unitPrice = unitPrice; } public float calculation() { return quantity * unitPrice; } public void show() { System.out.println(name + "(数量:" + quantity + ",单价:" + unitPrice + "元)"); } } // branch member: Bag class Bags the implements Articles { Private String name; // name Private the ArrayList <Articles> Bags = new new the ArrayList <Articles> (); public Bags(String name) { this.name = name; } public void add(Articles c) { bags.add(c); } public void remove(Articles c) { bags.remove(c); } public Articles getChild(int i) { return bags.get(i); } public float calculation() { float s = 0; for (Object obj : bags) { s += ((Articles) obj).calculation(); } return s; } public void show() { for (Object obj : bags) { ((Articles) obj).show(); } } }

  Test results are as follows:

You buy the product are:
Li Ning brand sports shoes (Quantity: 1 Price: 198 .0 million)
Shaoguan mushrooms (Quantity: 2, Unit: 69 .0 million)
Shaoguan tea (Number: 3, Price: 180 .0 million)
Jingdezhen porcelain (Quantity: 1, Price: 380 .0 million)
Wuyuan Specialties (Quantity: 2, Unit: 7 .9 million)
Wuyuan map (Quantity: 1, Price: 9 .9 million)
The total price to be paid is: 1279.7 yuan

Scene Five applications, the combination mode

  Previous analysis of the structure and characteristics of the combination pattern, it applies the following analysis scenarios.

  • In the case of a need to represent the whole object is part of the hierarchy.
  • Different requirements, the user can use a unified interface for all objects using the case of composite structures hidden from the user in combination with a single target object.

Extended Six, the combination mode

  If the combination of modes previously described in the leaf nodes and branches abstract nodes, i.e. leaf nodes and branch nodes also have child nodes, then the combination patterns will be extended to complex combinations of patterns, such as Java AWT / Swing in simple assembly JTextComponent subclasses for JTextField, JTextArea, container container assembly has subclasses Window, Panel. A complex combination pattern configuration diagram as shown:  

          

Guess you like

Origin www.cnblogs.com/jing99/p/12602749.html