This is the 20th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Author’s other platforms:

| CSDN:blog.csdn.net/qq\_4115394…

| the nuggets: juejin. Cn/user / 651387…

| zhihu: www.zhihu.com/people/1024…

| GitHub:github.com/JiangXia-10…

| public no. : 1024 notes

This article is about 2,548 words and will take about 10 minutes to read

What are behavioral design patterns

The previous articles covered creative and structural design patterns, respectively, and the next few articles will cover behavioral design patterns.

The Creational Pattern refers to the abstraction of the instantiation process of a class, allowing the creation and use of objects in a software module to be separated. For these objects, the outside world only needs to know their common interface, but does not need to know their specific implementation details, which makes the system design more in line with the principle of single responsibility, and the software structure is more clear.

Structural Pattern refers to how to combine classes or objects together to form a larger structure, and form a complex and more powerful Structural system through various combination forms.

Behavioral Pattern refers to the abstraction of assigning responsibilities and algorithms to different objects.

It focuses not only on the structure of classes and objects, but also on their interactions. Behavioral patterns allow for a clearer division of responsibilities between classes and objects.

Behavioral pattern can be divided into class behavior pattern and object behavior pattern:

Class behavior pattern: The behavior pattern of a class uses inheritance relationships to distribute behavior among several classes. Class behavior pattern mainly distributes responsibilities of parent and subclass by means of polymorphism.

Object behavior pattern: The object behavior pattern uses the aggregate association of objects to assign behaviors. The object behavior pattern mainly assigns responsibilities of two or more classes through object association. According to the “principle of composite reuse”, the system should be as far as possible

Most behavior design patterns belong to object behavior design patterns by using association instead of inheritance.

The first behavioral design pattern introduced is the —- visitor pattern!

define

The visitor pattern refers to the separation of operations on elements of a data structure into separate classes that can define new operations on those elements without changing the data structure. It’s a behavioral design pattern! It is also one of the most complex patterns in the behavior class, and one of the most used behavioral design patterns!

Part of the

The visitor pattern consists of the following parts:

1. Visitor Is mainly used to define an interface to access a specific element, and there is an access operation method for each specific element class, and the parameter type in this operation identifies the specific element to be accessed.

ConcreteVisitor: This implements the access operations declared in the abstract visitor role, determining what a visitor should do when accessing an element.

Element: Declare an interface that contains the receiving operation, and accept the visitor object as the parameter of the receiving method.

Concrete Elements: Implement accept operations provided by abstract element roles. Concrete elements may also contain operations related to their own business logic.

5. Object Structure: A container of elements, usually a container containing multiple different classes and interfaces, provides methods for visitors to iterate over all the elements in the container, usually implemented by aggregation classes such as List, Set, Map, etc., but this role is rarely abstracted in projects.

chestnuts

To start with a simple example, declare an abstract Visitor:

public interface Visitor {
    public void visit(ConcreteElement1 el1);
    public void visit(ConcreteElement2 el2);
}
Copy the code

We then declare an abstract Element, Element ConcreteElement, and inherit the abstract Element:

public abstract class Element { public abstract void accept(Visitor visitor); public abstract void print(); } public class ConcreteElement1 extends Element{ @Override public void accept(Visitor visitor) { visitor.visit(this); } @override public void print(){system.out.println (" This is ConcreteElement1"); } } public class ConcreteElement2 extends Element { @Override public void accept(Visitor visitor) { visitor.visit(this);  } @override public void print() {system.out.println (" This is ConcreteElement2"); }}Copy the code

Then define a ConcreteVisitor ConcreteVisitor that implements the Visitor interface:

public class ConcreteVisitor implements Visitor { @Override public void visit(ConcreteElement1 el1) { el1.print(); } @Override public void visit(ConcreteElement2 el2) { el2.print(); }}Copy the code

The last part is the Object Structure, the code is as follows:

public class ObjectStruture { public static List<Element> getList(){ List<Element> list = new ArrayList<Element>(); Random ran = new Random(); for(int i=0; i<10; i++){ int a = ran.nextInt(100); if(a>50){ list.add(new ConcreteElement1()); }else{ list.add(new ConcreteElement2()); } } return list; }}Copy the code

Finally, the final test code:

public class VisitorPatternTest { public static void main(String[] args) { List<Element> list = ObjectStruture.getList(); for(Element e: list){ e.accept(new ConcreteVisitor()); }}}Copy the code

The running results are as follows:

From the example above, you can summarize the characteristics (strengths and weaknesses) of the visitor pattern.

Advantages of the visitor pattern

1. As mentioned earlier, the visitor pattern is consistent with the single responsibility principle. In visitor design pattern code, the operations that need to be encapsulated in a visitor in an element class must be those that have little to do with the element class itself and are volatile, and using the visitor pattern on the one hand complies with the single responsibility principle.

2. As you can see from the above code, the visitor pattern scales well because encapsulated operations are generally mutable, and element classes can extend different operations by accepting different visitors. So when changes occur, you can extend the changing part without changing the element class itself.

3. Good reuse of visitor pattern code. This improves system reuse by allowing visitors to define common functions throughout the object structure.

4. Flexibility in visitor mode. Because the visitor pattern decouples the data structure from the operations acting on it, the set of operations can evolve relatively freely without affecting the system’s data structure.

Disadvantages of the visitor pattern

The disadvantages of the visitor pattern are also obvious:

1. Difficulty in adding new element classes to visitor pattern code. Since adding a new element class requires adding a specific action to each specific visitor class, this clearly violates the “open close principle.”

2. It violates the principle of dependency inversion. Because the visitor pattern relies on concrete classes, not abstract ones.

Applicable scenario

1. If there are operations on an object that are not related to the object, you can use the Visitor pattern to encapsulate these operations in the visitor to avoid affecting the object.

2. Or similar operations exist in a group of objects. To avoid a lot of repetitive code, these repeated operations can also be encapsulated in visitors.

3. Object structures contain objects of many types, and you want to perform operations on these objects depending on their specific types

4, the object structure is relatively stable, but its operating algorithm often changes system

conclusion

So that’s an introduction to the visitor design pattern in behavioral design patterns.

The visitor pattern refers to the separation of operations on elements of a data structure into separate classes that can define new operations on those elements without changing the data structure.

This article and all of the previous design pattern examples will be synchronized to Github, if you need to download star!

Github address: github.com/JiangXia-10…

Related recommendations:

Learning Design Patterns from Scratch part 1: What are Design Patterns

Learning design Patterns from scratch (PART 2) : Singleton patterns

Learning design Patterns from Scratch (3)

Learning design Patterns from Scratch (4) : Factory Pattern

Learning Design Pattern from Scratch (5) : Builder Pattern

Learning design Patterns from Scratch (6) : Adapter Pattern

Learn design Pattern from scratch (6) : Proxy Pattern

Decorator Pattern ()

Learning design Patterns from Scratch (9) : Facade Pattern

Learning design Patterns from Scratch (10) : Bridge Pattern

Learning Design Patterns from Scratch (11) : Composite Pattern

Learn design Pattern from scratch (12) : Flyweight Pattern