[Design Mode]-Combination Mode

1. Introduction to combination mode

1. What is combined mode

The composite pattern (composite pattern) is a kind of structure-oriented design pattern, also called the partial overall pattern. This mode is to solve the problem of displaying the hierarchical structure of a group of similar objects, combining the objects into a tree structure to represent the part-whole hierarchical structure. The combination mode makes the user's use of the single pair of love and the combined object consistent.

2. Usage scenarios of combined mode

Usually combined mode is used in two scenarios:

  1. When you want to represent parts of the object-the overall hierarchy (tree structure)
  2. You want users to ignore the difference between the overall object and the single object, and the user will use all objects in the combined structure uniformly

2. Tell the combination mode through business scenarios

1. Propose a usage scenario

To give a simple example, in fact, the file system of our computer is a very typical tree structure. For example, when we want to save a file, the operating system will let us choose a save path, then we simply analyze whether this path is an obvious hierarchical relationship.
Insert picture description here

First of all, here, D: represents the target disk we want to store, and Users\GIF is the path we want to save. This path is composed of multiple folders, and each level of folder may not There is only one subordinate folder. For example, we can see when we open the GIF folder: In
Insert picture description here
other words, there may be multiple subordinate folders under each folder. Here we use a structure diagram to illustrate:
Insert picture description here

Assuming that the file system structure of Disk D in our computer is as follows, then I want to create a simple model to show this system structure. What should I do?

2. Business Analysis

First, let's analyze a business attribute of this file system. First of all, whether it is Disk D or the lower-level folder directory, both have the function and attribute of maintaining files. In short, it is possible to add, delete, modify, and check related operations on files. Secondly, they all have certain inherent attributes, such as name, size, etc. Can we separate these common attributes and behaviors to achieve the purpose of function reuse and convenient expansion and maintenance? Of course it is possible. The extraction of all the common parts here is the first abstract root node (component) of the composition model . Component is the object declaration interface in the composite mode. It is mainly responsible for defining the common behaviors and attributes of all classes for the convenience of business parties to access and manage subclasses. With the abstract root node, what we need to analyze next is the function of folders at all levels. They are mainly used to store files. If we compare the entire file system to a tree, then each level of folder is the tree's Branches, and the files stored in each folder are the leaves of this tree. Then the role of the branch in the composite system is the branch node (composite) , and the composite is mainly used to store the child nodes. The files of each format in the last layer of the entire file system do not have the ability to store nodes, so they are like the leaves of a tree, playing the role of **leaf**, leaf There are no other branches below, it is the smallest unit of the combined mode system hierarchy. Then we will convert the system structure diagram according to the model we analyzed, and we can see that
Insert picture description here
this structure is the basic structure of the combined model. Of course, on the basis of the structure, there are also two types of combination modes for the degree of separation from the business.

3. Classification and realization of combination mode

There are usually two implementations of the combination mode: transparent mode and safe mode . The main difference between the two modes is that the transparent mode puts all the common behaviors of the combination into the component, so that nodes at different levels have consistent behaviors. The advantage of doing this is that the client does not need to distinguish which level of nodes it is and can be used uniformly, but the disadvantage is obvious. The leaf nodes will inherit behaviors that are useless to him. Therefore, the safe mode is to solve this problem. In the safe mode, the component will only extract the basic behavior, and the method of the branch node and the leaf node itself needs to be implemented in itself.

1. The realization of transparent combination mode

Not much to say, we use a transparent combination mode to achieve a file system-level traversal function;

(1) Create component

public abstract class FileComponent {
    
    

	protected String name;

	// 限制文件创建时 必须拥有自己的名字
	public FileComponent(String name) {
    
    
		super();
		this.name = name;
	}

	// 允许获取名称
	public String getName() {
    
    
		return name;
	}

	// 允许修改名称
	public void setName(String name) {
    
    
		this.name = name;
	}

	// 添加下级节点
	public void add(FileComponent fileComponent) {
    
    
		throw new UnsupportedOperationException("暂不支持该方法");
	}

	// 查询
	public abstract void print();

}

(2) Create composite

public class FileComposite extends FileComponent {
    
    
	private List<FileComponent> FileComposite = new ArrayList<FileComponent>();

	public FileComposite(String name) {
    
    
		super(name);
	}

	@Override
	public void add(FileComponent fileComponent) {
    
    
		FileComposite.add(fileComponent);
	}

	@Override
	public void print() {
    
    
		System.out.println(getName());
		for (FileComponent fileComponent : FileComposite) {
    
    
			System.out.print("  -");
			fileComponent.print();
		}
	}

}

(3) Create leaf

public class FileLeaf extends FileComponent {
    
    

	public FileLeaf(String name) {
    
    
		super(name);

	}

	@Override
	public void print() {
    
    
		System.out.println("-" + getName());
		System.out.println("-------------");

	}

}

(4) Create test cases and test results

public class Test {
    
    

	public static void main(String[] args) {
    
    
		FileComponent fileComposite = new FileComposite("D:");
		FileComponent users = new FileComposite("Users");
		FileComponent game = new FileComposite("game");
		fileComposite.add(users);
		fileComposite.add(game);
		FileComponent gif = new FileComposite("动图");
		users.add(gif);
		FileComponent fileLeaf = new FileLeaf("组合模式.gif");
		gif.add(fileLeaf);
		fileComposite.print();
	}
}

Test result:
Insert picture description here
Here we observe that a file-level traversal system has been designed. The new file method here is implemented by us withdrawing from the Component. Obviously this method is not needed by the leaf node, so we can further optimize this code and put the functions that the leaf node does not need into the composite. Realize in each.

2. The realization of safe combination mode

(1) Create Component

public abstract class FileComponent {
    
    

	protected String name;

	public FileComponent(String name) {
    
    
		super();
		this.name = name;
	}

	public String getName() {
    
    
		return name;
	}

	public void setName(String name) {
    
    
		this.name = name;
	}

	public abstract void print();
}

(2) Create Composite

public class FileComposite extends FileComponent {
    
    

	private List<FileComponent> FileComposite = new ArrayList<FileComponent>();

	public FileComposite(String name) {
    
    
		super(name);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void print() {
    
    
		System.out.println(getName());
		for (FileComponent fileComponent : FileComposite) {
    
    
			System.out.print("  -");
			fileComponent.print();
		}
	}

	public void add(FileComponent fileComponent) {
    
    
		FileComposite.add(fileComponent);
	}

}

(3) Create leaf

public class FileLeaf extends FileComponent {
    
    

	public FileLeaf(String name) {
    
    
		super(name);
	}

	@Override
	public void print() {
    
    
		System.out.println("-" + getName());
		System.out.println("-------------");
	}

}

(4) Create test cases and test results

public class Test {
    
    

	public static void main(String[] args) {
    
    
		FileComposite fileComposite = new FileComposite("D:");
		FileComposite users = new FileComposite("Users");
		FileComposite game = new FileComposite("game");
		fileComposite.add(users);
		fileComposite.add(game);
		FileComposite gif = new FileComposite("动图");
		users.add(gif);
		FileComponent fileLeaf = new FileLeaf("组合模式.gif");
		gif.add(fileLeaf);
		fileComposite.print();
	}
}

Test Results:
Insert picture description here

Fourth, summarize the combination model

1. The composition of the combined model

The combination model is divided into three roles:

  1. Abstract root node (compoent) : Responsible for defining the common attributes and methods of each level of the system, and can also pre-implement some default behaviors and attributes.
  2. Branch node (composite) : Responsible for storing child nodes, with the common attributes and behaviors of the system.
  3. Leaf node (leaf) : A leaf node, which has no branches below it, is the smallest unit of the system hierarchy.

2. Structure diagram of combined mode

As shown:
Insert picture description here

3. Advantages and disadvantages of combined mode

advantage:

  1. The combination mode extracts the public attributes of the system and hides the differences between objects, so that the business system can ignore the differences when using it, and use consistent behaviors to control different levels.
  2. It is easy to add lower-level nodes without intruding into existing class libraries and conforming to the principle of opening and closing.

Disadvantages:

  1. If the tree structure is too large, the deep traversal of the system may cause the running time to be too long.
  2. Combination mode violates the principle of dependency inversion

4. The use of combined mode in JDK

The implementation of the Map class in the JDK refers to the combination mode. Interested students can browse the source code and materials to view by themselves. I won't go into details here.

Okay, this concludes today's content. If you have any questions, you can privately message me or leave a message in the comment area, and I will answer you as soon as possible. Friends who feel rewarded, please remember one-click three consecutive times, pay attention to bloggers, don’t get lost, and refuse to be a prostitute~

Guess you like

Origin blog.csdn.net/xiaoai1994/article/details/112917978