It's been said many times. Design Pattern---combination mode

Source: Internet
Author: User
Tags abstract constructor stub

[Turn your rational mind slowly into a conditioned reflex]

In this paper, we talk about the composition model, the article structure of the topic is consistent with the above. Practice, let's take a look at the environment of our example project:

Operating system: Win7 x64

Other software: Eclipse MARS,JDK7

--------------------------------------------------------------------------------------------------------------- ---------------------- Classic Questions:

The directory structure of a file system, the organizational structure of a company or a government department, and the abstract organizational structure of a tree-like recursive relationship. Thinking Analysis:

Point one: Each level can be used as a complete minimum tree structure.

Point two: The external performance of each level is similar, has the function of shielding hierarchy structure. For example, the file system at different levels of the directory has the same representation. The same department set up in the hierarchical Administrative office organization structure.

Point three: For software implementations, you need to increase the code reuse as much as possible. Example Project:


Combining pattern Template Code "in this case, we'll show the template code, and we'll demonstrate a concrete example later."


Create a Component.java file with the following details:

Package com.csdn.ingo.gof_Composite;

Public abstract class component{
	protected String name;
	Public Component (String name) {
		this.name = name;
	}
	public abstract void Add (Component c);
	public abstract void Remove (Component c);
	public abstract void display (int depth);
}
Create a Composite.java file with the following details:

Package com.csdn.ingo.gof_Composite;

Import java.util.ArrayList;
Import java.util.List;
public class Composite extends Component {
	private list<component> children = new Arraylist<component> () ;
	
	Public Composite (String name) {
		super (name);
		Todo auto-generated constructor stub
	}

	@Override public
	void Add (Component c) {
		//TODO auto-generated method Stub
		Children.add (c);
	}

	@Override public
	void Remove (Component c) {
		//TODO auto-generated method stub
		Children.remove (c);
	}

	@Override public
	void display (int depth) {
		//TODO auto-generated method stub
		System.out.println ( "-" +name);
		for (Component c:children) {
			c.display (depth+1);}}
}
Create a Leaf.java file with the following details:

Package com.csdn.ingo.gof_Composite;

public class Leaf extends component{public

	leaf (String name) {
		super (name);
	}

	@Override public
	Void Add (Component c) {
		//TODO auto-generated method stub
		System.out.println ("Cannot add to the Leaf ");
	}

	@Override public
	void Remove (Component c) {
		System.out.println ("Cannot remove from a leaf");

	@Override public
	void display (int depth) {
		//TODO auto-generated method Stub
		System.out.println (New String ("----") + "depth:" +depth+ "Name:" +name);
	}
}
Create a Window.java file with the following details:

Package com.csdn.ingo.gof_Composite;

public class Window {public
	static void Main (string[] args) {
		Composite root = new Composite ("root");
		Root.add (New Leaf ("Leaf A"));
		Root.add (New Leaf ("Leaf B"));
		
		Composite comp = new Composite ("Compostex");
		Comp.add (The New Leaf ("Leaf XA"));
		Comp.add (New Leaf ("Leaf XB"));
		Root.add (comp);
		
		Composite comp2 = new Composite ("Compostexy");
		Comp2.add (New Leaf ("Leaf XYA"));
		Comp2.add (New Leaf ("Leaf XYB"));
		Comp.add (COMP2);
		Root.add (New Leaf ("Leaf C"));
		
		Leaf L = new leaf ("leaf D");
		Root.add (l);
		Root.remove (l);
		Root.display (1);
	}
}

"It may be difficult to see the above code directly. Give the code to you first crossing is the hope that the code will now run, observe the results. Here we introduce the relevant concepts and principles of " pattern Summary: composite pattern structure diagram:


Combination mode:

Combines objects into a property structure to represent a "partial-overall" hierarchy. The combined mode makes the user consistent with the use of individual objects and composite objects. components:

Component: Abstract artifacts. Can be an interface or an abstract class. It contains the declaration of the leaf and the composite public interface. such as, adding and modifying functions.

Leaf: leaf node. is actually the last level node, it can no longer have any form of impl or extend relationship. itself must implement the content defined in component.

Composite: Container component. is defined relative to the leaf. It is also capable of mounting other nodes (either leaf or composite). Where you can recursively implement calls to child parts.

"Above, you can analogy folders in the file system, folders can contain files or folders, the file itself cannot contain other files or folders"

Special Note: The template code above contains the add and remove methods in both the leaf and the composite. But in fact, only the composite method is effective. Actual scenario use case: requirements Description:

The company includes: subsidiaries, manpower, research and development, finance. Subsidiaries include: subsidiaries (optional), manpower, research and development, finance. Wait a minute. Example code:


Create a Company.java file with the following details:

Package com.csdn.ingo.gof_Composite.one;

Public abstract class company{
	protected String name;
	Public company (String name) {
		this.name = name;
	}
	public abstract void Add (Company C);
	public abstract void Remove (company C);
	public abstract void display (int depth);
	public abstract void Lineofduty ();
}
Create a Concretecompany.java file with the following details:

Package com.csdn.ingo.gof_Composite.one;

Import java.util.ArrayList;
Import java.util.List;

public class Concretecompany extends company {
	private list<company> children = new Arraylist<company> () ;
	
	Public Concretecompany (String name) {
		super (name);
		Todo auto-generated constructor stub
	}

	@Override public
	Void Add (Company C) {
		//Todo auto-generated Method Stub
		Children.add (c);
	}

	@Override public
	void Remove (Company C) {
		//TODO auto-generated method stub
		Children.remove (c);
	}

	@Override public
	void display (int depth) {
		//TODO auto-generated method stub
		System.out.println ( "-" +name);
		For (company C:children) {
			c.display (depth);
		}
	}

	@Override public
	void Lineofduty () {
		//TODO auto-generated method stubs for
		(company C:children) {
			C.lineofduty ();}}}

Create a Financedepartment.java file with the following details:

Package com.csdn.ingo.gof_Composite.one;

public class Financedepartment extends company{public

	financedepartment (String name) {
		super (name);
	}

	@Override public
	Void Add (Company C) {
		//TODO auto-generated method stubs
		
	}

	@Override public
	Void Remove (Company C) {
		//TODO auto-generated method stubs
		
	}

	@Override public
	void display (int depth) { c14/>//TODO auto-generated Method stub
		System.out.println ("----" +name);

	@Override public
	void Lineofduty () {
		//TODO auto-generated method stub
		System.out.println ("Finance Duty: "+name);
	}
}
Create a Hrdepartment.java file with the following details:

Package com.csdn.ingo.gof_Composite.one;

public class Hrdepartment extends company{public

	hrdepartment (String name) {
		super (name);
	}

	@Override public
	Void Add (Company C) {
		//TODO auto-generated method stubs
		
	}

	@Override public
	Void Remove (Company C) {
		//TODO auto-generated method stubs
		
	}

	@Override public
	void display (int depth) { c14/>//TODO auto-generated Method stub
		System.out.println ("----" +name);

	@Override public
	void Lineofduty () {
		//TODO auto-generated method stub
		System.out.println ("HR Duty:" + name);
	}
}

Create a Window.java file with the following details:

Package com.csdn.ingo.gof_Composite.one;


public class Window {public
	static void Main (string[] args) {;
		Company root = new Concretecompany ("head Office");
		Root.add (New Hrdepartment ("Head Office Human Resources Department"));
		Root.add (New Financedepartment ("head Office Finance Department"));

		Concretecompany comp1 = new Concretecompany ("Shanghai Branch");
		Comp1.add (New hrdepartment ("Shanghai Branch Human Resources department"));
		Comp1.add (New financedepartment ("Shanghai Branch Finance Department"));
		Root.add (COMP1);
		
		Concretecompany comp2 = new Concretecompany ("Nanjing Branch");
		Comp2.add (New Hrdepartment ("Nanjing Branch Human Resources department"));
		Comp2.add (New Financedepartment ("Nanjing Branch Finance Department"));
		Root.add (COMP2);
		
		Root.display (1);
		Root.lineofduty ();

	}
}

Note: In contrast to the template code, the root object can also be an abstract class company. However, specific organizations need to be specifically stated as concrete implementations.

mode extension:

In the above, we say that only add and remove in composite are valid.

In fact, the settings of these methods become transparent combined mode in the combination mode, safe combination mode. That is, in the transparent combination mode, these methods do not distinguish between leaf and composite. Specific applications can be returned by changing the return value or by exception information. The security mix pattern, however, requires that the parent class not provide the declaration of the method, but rather be declared by composite, so that it is necessary to declare the leaf and the composite two objects in the window main class. Reflection: Application Scenarios:

When you have a tree-hierarchical relationship with a whole and a part, you want to shield the differences between layers by the same structure. The functions of different tree hierarchies are similar, and want to achieve the purpose of reuse. The hierarchy relationship is not fixed and needs to be modified as required.

Advantages:

The combination pattern clearly defines a complex relationship. It also masks this complexity and differentiation to the client. The client uses any one of the relationships in the tree structure, which can be done through a unified interface. Effectively reduce the dependency of the client. The adjustment of the tree structure is very convenient. and the tree structure itself can be very complex.

Disadvantages:

There is not enough constraint on the tree hierarchy. For example, in the organization relationship processing, the subsidiaries do not need to set up the * * Department, but because there is no mandatory constraints, the client can be arbitrarily modified.

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

So far, the design pattern that has been said many times---the end of combination mode


Resources:

Book: "Big Talk design mode"

Other Posts: http://blog.csdn.NET/lovelion/article/details/7563445


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.