当前位置:网站首页>Visitor pattern
Visitor pattern
2022-06-29 04:23:00 【Change with affection】
Visitor mode
In visitor mode (Visitor Pattern) in , We used a visitor class , It changes the execution algorithm of the element class . In this way , The execution algorithm of the element can change as the visitor changes . This type of design pattern belongs to behavioral pattern . According to the pattern , The element object has accepted the visitor object , This allows the visitor object to handle operations on the element object
do .
- Visitor mode (Visitor Pattern), Encapsulate operations that act on elements of a data structure , It can define new operations on these elements without changing the data structure .
- Mainly separate data structure and data operation , Solve the problem of data structure and operation coupling
- The basic principle of visitor mode is : Add an interface to the visited class to receive visitors
- The main application scenario of visitor mode is : There are many different operations that need to be performed on objects in an object structure ( These operations are not related to each other ), At the same time, these operations need to be avoided " Pollution " Classes for these objects , You can choose visitor mode to solve
Case study : Visitor mode
Divide the audience into men and women , Evaluate the singers , After watching a singer perform , Get their different comments on the singer ( There are different kinds of evaluations , Like success 、 Failure, etc )
public abstract class Action {
// Get men Evaluation of
public abstract void getManResult(Man man);
// Get the women Evaluation
public abstract void getWomanResult(Woman woman);
}
public abstract class Person {
// Provide a method , Let visitors visit
public abstract void accept(Action action);
}
public class Man extends Person {
@Override
public void accept(Action action) {
action.getManResult(this); }
}
//1. Double dispatch is used here , First of all, in the client program , Pass the specific state as a parameter Woman in ( First distribution )
//2. then Woman Class as a parameter " The specific methods " Medium method getWomanResult, At the same time, I will (this) As a parameter
// Pass in , Complete the second assignment
public class Woman extends Person{
@Override
public void accept(Action action) {
action.getWomanResult(this); }
}
public class Success extends Action {
@Override
public void getManResult(Man man) {
System.out.println(" The man said that the singer was successful .."); }
@Override
public void getWomanResult(Woman woman) {
System.out.println(" The woman rated the singer as a success ..");}
}
public class Fail extends Action {
@Override
public void getManResult(Man man) {
System.out.println(" The evaluation given by the man failed the singer !"); }
@Override
public void getWomanResult(Woman woman) {
System.out.println(" The singer failed in the woman's evaluation !"); }
}
// data structure , Manage a lot of people (Man , Woman)
public class ObjectStructure {
// Maintains a collection
private List<Person> persons = new LinkedList<>();
// Add to list
public void attach(Person p) {
persons.add(p); }
// remove
public void detach(Person p) {
persons.remove(p); }
// Show the evaluation
public void display(Action action) {
for(Person p: persons) {
p.accept(action);
}
}
}
public class Client {
public static void main(String[] args) {
// establish ObjectStructure
ObjectStructure objectStructure = new ObjectStructure();
objectStructure.attach(new Man());
objectStructure.attach(new Woman());
// success
Success success = new Success();
objectStructure.display(success);
System.out.println("===============");
Fail fail = new Fail();
objectStructure.display(fail);
}
}
Comply with the opening and closing principle and add one wait undetermined
public class Wait extends Action {
@Override
public void getManResult(Man man) {
System.out.println(" The man's comment is that the singer is to be determined .."); }
@Override
public void getWomanResult(Woman woman) {
System.out.println(" The woman's comment is that the singer is to be determined .."); }
}
test
System.out.println("======= It's a test to be determined ========");
Wait wait = new Wait();
objectStructure.display(wait);
Summary - Double distribution
- Double dispatch is mentioned above , Double dispatch means no matter how the class changes , We can all find the desired way to run . Double dispatch means that the operation to be performed depends on the type of request and the type of two receivers
- Take the example above , Suppose we add one by one Wait State class of , Investigate Man Classes and Woman Class , Because of the use of double dispatch , Just add one Action The subclass can be called on the client , No need to change the code of any other class .
summary
advantage
- The visitor model is consistent with the principle of single responsibility 、 Let the program have excellent expansibility 、 Very flexible
- Visitor mode can be used to integrate functions -, Report can be made 、UI、 Interceptors and filters , It is suitable for systems with relatively stable data structure
shortcoming - Specific elements to visitors to publish details , That is to say, visitors pay attention to the internal details of other classes , This is not what Dimitar's Law suggests , This makes it difficult to change specific elements
- Contrary to the principle of dependence reversal . Visitors rely on concrete elements , Rather than abstract elements
- therefore , If a system has a relatively stable data structure , There are constantly changing functional requirements , So the visitor model is more appropriate .
边栏推荐
- On June 27, 2022, I have the right to choose the journey of the summer vacation.
- Five thousand years of China
- 剑指 Offer II 040. 矩阵中最大的矩形
- SQL 数据记录如何上下行合并
- 如何创建 robots.txt 文件?
- [C language] explain the thread exit function pthread_ exit
- String differences between different creation methods
- How to quickly change the database name in MySQL
- CDC2.2.1还不支持postgresql14.1么?基于pgbouncer连接方式下,以5433
- Is the interviewer too difficult to serve? A try catch asks so many tricks
猜你喜欢

Inftnews | metauniverse technology will bring a new shopping experience

Hcie security day41: theoretical learning: information collection and network detection

【HackTheBox】dancing(SMB)

Open source demo| you draw and I guess -- make your life more interesting

What are the MySQL database constraint types

Apifox : 不仅是Api调试工具,更是开发团队的协作神器

ROS TF coordinate transformation Library & rewrite to create high frequency coordinate transformation broadcaster

SQL 数据记录如何上下行合并

Error accessing database

How to merge upstream and downstream SQL data records
随机推荐
Installation and configuration of interrealsense d435i camera driver
Redis cache penetration, cache breakdown, cache avalanche
Talking about Canary deployment
ECS 4 sync point, write group, version number
剑指 Offer II 040. 矩阵中最大的矩形
PostgreSQL has a cross database references are not implemented bug
The five levels of making money, which level are you on?
快速开发项目-VScode插件
IDEA修改jvm内存
Analysis on the types of source code anti leakage technology
【Laravel系列8】走出 Laravel 的世界
SQL database stored procedure writing method
[WC2021] 斐波那契——数论、斐波那契数列
Cisco voice card handling configuration
Go Foundation (I)
Ask a simple question about SQL
1018 hammer scissors cloth
Developer scheme · environmental monitoring equipment (Xiaoxiong school IOT development board) connected to graffiti IOT development platform
Pytorch read / write file
yolox出现 RuntimeError: DataLoader worker (pid(s) 17724, 1364, 18928) exited unexpectedly