The composite mode is targeted at specific scenarios, such as file management, organization management, etc. It simplifies management and makes the code very simple.

UML class diagrams location: www.processon.com/diagraming/…

This article is linked to: github.com/shidawuhen/…

Definition 1.

1.1 Combination Mode

Composition pattern: Grouping objects into a tree structure to represent a partial-whole hierarchy. The composite pattern makes the use of single objects and composite objects consistent.

UML:

1.2 analysis

UML diagrams alone may not be clear, but it is easier to cite them. Composite is the directory, Leaf is the file in the directory, and both directories and files inherit from Component. A directory can add or delete files and display the directory location. A file can display only the file location.

There are two ways to implement the directory requirement.

The first does not use the composite pattern, but uses a single class with two core variables

  • A member variable indicates whether the object is a file or directory

  • A member variable that stores a list of files in a directory and is null if the object is a file

Type FileSystemNode struct {isFile bool subNodes []FileSystemNode struct {isFile boolCopy the code

The second option uses a composite pattern. Although the first solution can achieve the function of file management, it is not elegant. Because files and directories are different and have their own characteristics, putting unique content into a single class does not meet the single responsibility principle.

So we can split it into two classes: a file class and a directory class. The two classes must inherit from the same parent class. In addition to the repeated functions that can be reused, subNodes do not need to make any distinction between the two classes. And the two classes can evolve independently without affecting each other, so why not?

2. Application scenarios

In use, the combination mode, especially like depth-first traversal or breadth-first traversal, is generally used in organizational structure and document management. These functions have something in common: individuals and groups are very similar in function and cognition.

Bytedance’s collaborative office software, Feizhu, is extremely suitable for using the combined mode in the document management section. You can try it if you have time. The link is as follows: www.feishu.cn/.

3. Code implementation

This code simply implement directory and file add, display function bar.

package main import "fmt" const Separator = "--" /** * @Author: Jason Pang * @Description: */ type FileSystemNode interface {Display(separator string)} /** * @author: */ type FileCommonFunc struct {fileName string} /** * @author: Jason Pang * @Description: Set the fileName * @receiver f * @param fileName */ func (f *FileCommonFunc) SetFileName(fileName string) {f.filename = fileName } /** * @author: Jason Pang * @description: file */ type FileNode struct {FileCommonFunc} /** * @author: Jason Pang * @Description: * @receiver f */ func (f *FileNode) Display(separator String) {fmt.Println(separator + f.filename +" } /** * @author: Jason Pang * @description: */ type DirectoryNode struct {FileCommonFunc Nodes []FileSystemNode} /** * @author: Jason Pang * @description: Separator string (separator string) {separator + d. filename) for _, separator string (separator + d. filename) for _,  node := range d.nodes { node.Display(separator + Separator) } } /** * @Author: Jason Pang * @Description: Add directory or file * @receiver d * @param f */ func (d *DirectoryNode) Add(f FileSystemNode) {d.nodes = append(d.nodes, Func main() {// Initialize biji := DirectoryNode{} biji.setfilename (" note ") huiyi := DirectoryNode{} huiyi.setfilename (" meeting ") Chenhui := FileNode{} chenhui.setfilename (" morning.md ") zhouhui := FileNode{} zhouhui.setfilename (" week.md ") // assemble Add(&chenhui) huiyi.Add(&chenhui) huiyi.Add(&zhouhui) // Display biji.Display(Separator)}Copy the code

Display:

➜ myproject go run main.go

– notes

– meeting

—— Morning meeting. Md: Hello, world

—— Weekly meeting. md The contents of the file are Hello, world

Both file and directory classes implement the FileSystemNode interface, so directory classes manage file classes as if they were managing themselves. Both combine the FileCommonFunc class to reuse the same functionality. Finally, the two can be changed independently. For example, the directory class has the Add function, but the file class does not.

3. Summary

Composite modes are useful for specific scenarios, so it’s up to luck if you can use them. This design pattern satisfies the single responsibility principle, open and close principle and Richter’s substitution principle.

The last

If you like my article, you can follow my public account (Programmer Malatang)

My personal blog is shidawuhen.github. IO /

Review of previous articles:

recruitment

  1. Bytes to beat | push big 24:00

  2. Bytes to beat | headlines today guangzhou server push r&d engineers

  3. Bytes to beat | trill electricity now hiring front-end development project in Shanghai

  4. Bytes to beat | trill electricity senior server-side development engineer – trading in Shanghai

  5. Bytes to beat | trill electric ShangWuHan server-side development engineer (senior)

  6. Bytes to beat | fly book big customer push product manager

  7. Bytes to beat | trill electricity service side technical posts vacant

  8. Bytedance recruitment special

Design patterns

  1. Go Design Mode (15)- Facade mode

  2. Go Design Pattern (14)- Adapter pattern

  3. Go Design Mode (13)- Decorator mode

  4. Go Design Mode (12)- Bridge mode

  5. Go Design Pattern (11)- Proxy pattern

  6. Go Design Mode (10)- Prototype mode

  7. Go Design Mode (9)- Builder mode

  8. Go Design Pattern (8)- Abstract Factory

  9. Go Design Mode (7)- Factory Mode

  10. Go Design Pattern (6)- Singleton pattern

  11. Go Design Pattern (5)- Class diagram symbolic representation

  12. Go Design Pattern (4)- Code writing optimization

  13. Go Design Pattern (4)- Code writing

  14. Go Design Patterns (3)- Design principles

  15. Go Design Pattern (2)- Object-oriented analysis and design

  16. Go Design Pattern (1)- Syntax

language

  1. No more fear of not getting Gin request data

  2. Understand pprof

  3. Go tool generate

  4. Go singleton implementation scheme

  5. Implementation principle of Go channel

  6. Implementation principle of Go timer

  7. Beego framework use

  8. Golang source BUG tracking

  9. Gin framework concise version

  10. Gin source code analysis

architecture

  1. The paging check pit is designed

  2. Payment access general issues

  3. Current limiting 2

  4. Seconds kill system

  5. Distributed systems and consistency protocols

  6. Service framework and registry for microservices

  7. Discussion on Micro-service

  8. Current limiting implementation 1

  9. CDN request process details

  10. Common Cache tips

  11. How to effectively connect with third-party payment

  12. Algorithm is summarized

storage

  1. MySQL database sub-database sub-table

  2. MySQL development specification

  3. Redis implements distributed locking

  4. The implementation principle of atomicity, consistency and persistence of transactions

  5. InnoDB locks and transactions

network

  1. HTTP2.0 basics tutorial

  2. HTTPS Configuration Combat

  3. HTTPS Connection Process

  4. TCP Performance Optimization

tool

  1. GoLand Practical skills

  2. Automatically generate go struct from mysql table

  3. Markdown editor recommends – Typora

Reading notes

  1. Selected by MAO

  2. The principle of

  3. History As A Mirror

  4. Agile revolution

  5. How to exercise your memory

  6. Simple Logic – After reading

  7. Hot Wind – After reading

  8. Analects of Confucius – After reading

  9. Sun Tzu’s Art of War – Reflections from reading

thinking

  1. A little review of the past

  2. Some thoughts on blogging

  3. The experience of calling 119 at night

  4. Struggle to mobilize all forces for victory

  5. Anti-liberalism

  6. practical

  7. The standard by which you judge yourself

  8. 2020 Blog Summary

  9. Service team holiday shift plan

  10. Project process management

  11. Some thoughts on project management

  12. Some thoughts on product manager

  13. Thinking about programmer career development

  14. Thinking about code review