当前位置:网站首页>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 .
边栏推荐
- The 30th day of force deduction (DP topic)
- 干货丨微服务架构是什么?有哪些优点和不足?
- MySQL can only add small tables when adding tables dynamically. If you increase the size of tables, you won't read data when running tasks. Is there any solution
- ROS TF coordinate transformation Library & rewrite to create high frequency coordinate transformation broadcaster
- NotImplementedError: Could not run torchvision::nms
- How to create robots Txt file?
- 从零到一,教你搭建「以文搜图」搜索服务(一)
- 直播预约|AWS Data Everywhere 系列活动
- PostgreSQL has a cross database references are not implemented bug
- Does cdc2.2.1 not support postgresql14.1? Based on the pgbouncer connection mode, with 5433
猜你喜欢

Wi-Fi 7 来啦,它到底有多强?

Inftnews | metauniverse technology will bring a new shopping experience

How to solve startup failure due to insufficient MySQL memory

SQL two columns become multi row filter display

Remediation for Unsafe Cryptographic Encryption

要不是和阿里P7聊过,我也不知道自己是个棒槌

LabVIEW显示Unicode字符

女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了

SqlServer如何查询除去整列字段为null的结果

JSX的基本使用
随机推荐
EEG signal processing - wavelet transform series
科班出身,结果外包都不要
webassembly学习-动态链接
Airflow2.2.3 + efficiency + MySQL 8 build a robust distributed scheduling cluster
ECS 4 sync point, write group, version number
不使用union实现Mysql 列转行
NotImplementedError: Could not run torchvision::nms
044. (2.13) add value to yourself
My creation anniversary
How to create a subtype like relationship between two generic classes when the classes are generic related
SEAttention 通道注意力機制
Analysis of moudo Network Library
Wi-Fi 7 来啦,它到底有多强?
c语言 --- 分支结构
Ask a simple question about SQL
How to solve startup failure due to insufficient MySQL memory
[C language] explain the thread exit function pthread_ exit
Path and LD_ LIBRARY_ Example of path usage
SQL database stored procedure writing method
043. (2.12) what will happen if you become enlightened?