当前位置:网站首页>Visitor model -- generation gap between young and middle-aged people
Visitor model -- generation gap between young and middle-aged people
2022-06-24 20:35:00 【zhanyd】
List of articles
Introduction
Xiaoshuai 25 year , Lao Wang 35 year , One day Xiaoshuai and Lao Wang discussed the increasingly obvious difference between young and middle-aged people .
Xiao Shuai listed several scenarios , At the same time, Xiaoshuai is the representative of young people , Lao Wang, as a representative of the middle-aged people, answered respectively .
1. When something goes wrong at work , It can't be solved immediately , For example, what if the leader is biased against you or the work task is too heavy ?
Xiaoshuai : Don't stay here , I have my own place , Change jobs immediately .
Lao Wang : Bear it first , Endure again , Maybe sometimes it comes to a running day , After all, there are so many mortgage payments to be made every month .
2. The year-end bonus was given , How to arrange ?
Xiaoshuai : Buy the latest mobile phone or other electronic products , Have a good time , Today's wine is today's wine .
Lao Wang : Take it all to repay the mortgage .
3. How to spend the weekend ?
Xiaoshuai : Two things , sleep , Play the game .
Lao Wang : Two things , Do housework , Bring baby .
No wonder young people and middle-aged people can't play together , This is the generation gap .
Lao Wang said : We said so much , Can you write the above dialogue in code ?
Xiaoshuai : I really flatter you , Everything can be related to code , That's ok , I'm in a good mood today , Let me show you .
Human abstract class :
/** * Human abstract class */
public abstract class Person {
/** * scene */
protected String scene;
public Person(String scene) {
this.scene = scene;
}
/** * answer */
public abstract void answer();
}
Young people :
/** * Young people */
public class Young extends Person{
public Young(String scene) {
super(scene);
}
@Override
public void answer() {
if(" The work is not going well ".equals(scene)) {
System.out.println(" Young people : Don't stay here , I have my own place , Change jobs immediately .");
} else if(" Annual bonus ".equals(scene)) {
System.out.println(" Young people : Buy the latest mobile phone or other electronic products , Have a good time , Today's wine is today's wine .");
} else if(" Over the weekend ".equals(scene)) {
System.out.println(" Young people : Two things , sleep , Play the game .");
}
}
}
Middle aged humans :
/** * middle-aged person */
public class MiddleAged extends Person{
public MiddleAged(String scene) {
super(scene);
}
@Override
public void answer() {
if(" The work is not going well ".equals(scene)) {
System.out.println(" middle-aged person : Bear it first , Endure again , Maybe sometimes it comes to a running day , After all, there are so many mortgage payments to be made every month .");
} else if(" Annual bonus ".equals(scene)) {
System.out.println(" middle-aged person : Take it all to repay the mortgage .");
} else if(" Over the weekend ".equals(scene)) {
System.out.println(" middle-aged person : Two things , Do housework , Bring baby .");
}
}
}
Client class :
/** * client */
public class Client {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Young(" The work is not going well "));
personList.add(new MiddleAged(" The work is not going well "));
personList.add(new Young(" Annual bonus "));
personList.add(new MiddleAged(" Annual bonus "));
personList.add(new Young(" Over the weekend "));
personList.add(new MiddleAged(" Over the weekend "));
personList.stream().forEach(f -> f.answer());
}
}
Output :
Young people : Don't stay here , I have my own place , Change jobs immediately .
middle-aged person : Bear it first , Endure again , Maybe sometimes it comes to a running day , After all, there are so many mortgage payments to be made every month .
Young people : Buy the latest mobile phone or other electronic products , Have a good time , Today's wine is today's wine .
middle-aged person : Take it all to repay the mortgage .
Young people : Two things , sleep , Play the game .
middle-aged person : Two things , Do housework , Bring baby .
Lao Wang, take a look , Say : Well written , But there are still some problems , If I want to add a few more problem scenarios , such as : What books do you usually read 、 What kind of sports do you like 、 What about sleeping at night ?
Xiaoshuai : It's not easy , Directly in Young and MiddleAged Class and if…else The conditions are OK !
Lao Wang shook his head and said : It's against Opening and closing principle : Turn off for changes , Open to expansion . If this is a class provided by a third party , You can't modify them , But add new behaviors , How do you do that ?
“ Without modifying the existing code , Add a new behavior to an existing class ? How could it be ?” Xiaoshuai doubted .
Lao Wang laughed : How impossible , There is a design pattern that does this .
Visitor mode
Visitor mode : Provides an operation that acts on elements in an object structure , You can do this without changing the element class , Define new actions that act on elements .
Visitor pattern is a behavior design pattern , Allows you to add new behaviors to the existing class hierarchy without modifying the existing code .

- Visitor( The visitor , Such as Scene)
Abstract class or interface , Declare which elements visitors can access . To be specific to the procedure is getYoungAnswer Method can access young object ;getMiddleAgedAnswer Method can access middleAged object . - ConcreteVisitor( Specific visitors , Such as WorkNotWell,YearEndAwards,Weekend)
Implementation class of visitor interface , Realize the concrete operation . - Element( Elements , Such as Person)
Interface or abstract class , Define a accept operation , Take a visitor as a parameter . - ConcreteElement( Specific elements , Such as Young and MiddleAged)
Realization accept operation , Usually visitor.visit(this) Pattern . - ObjectStructure( Object structure )
A collection of storage objects , It is convenient to traverse the elements .
Scene class :
/** * scene */
public interface Scene {
/** * The young man's answer * @param young */
public void getYoungAnswer(Young young);
/** * The answer of the middle-aged man * @param middleAged */
public void getMiddleAgedAnswer(MiddleAged middleAged);
}
Work is not going well :
/** * Bad work */
public class WorkNotWell implements Scene{
@Override
public void getYoungAnswer(Young young) {
System.out.println(young.name + ": Don't stay here , I have my own place , Change jobs immediately .");
}
@Override
public void getMiddleAgedAnswer(MiddleAged middleAged) {
System.out.println(middleAged.name + ": Bear it first , Endure again , Maybe sometimes it comes to a running day , After all, there are so many mortgage payments to be made every month .");
}
}
Year end bonus scenario :
/** * Annual bonus */
public class YearEndAwards implements Scene{
@Override
public void getYoungAnswer(Young young) {
System.out.println(young.name + ": Buy the latest mobile phone or other electronic products , Have a good time , Today's wine is today's wine .");
}
@Override
public void getMiddleAgedAnswer(MiddleAged middleAged) {
System.out.println(middleAged.name + ": Take it all to repay the mortgage .");
}
}
Weekend scene :
/** * Over the weekend */
public class Weekend implements Scene{
@Override
public void getYoungAnswer(Young young) {
System.out.println(young.name + ": Two things , sleep , Play the game .");
}
@Override
public void getMiddleAgedAnswer(MiddleAged middleAged) {
System.out.println(middleAged.name + ": Two things , Do housework , Bring baby .");
}
}
Human interface :
/** * Human interface */
public interface Person {
/** * Accept */
public void accept(Scene scene);
}
Young people :
/** * Young people */
public class Young implements Person{
protected String name;
public Young(String name) {
this.name = name;
}
@Override
public void accept(Scene scene) {
scene.getYoungAnswer(this);
}
}
Middle aged humans :
/** * middle-aged person */
public class MiddleAged implements Person{
protected String name;
public MiddleAged(String name) {
this.name = name;
}
@Override
public void accept(Scene scene) {
scene.getMiddleAgedAnswer(this);
}
}
Object structure class :
/** * Object structure */
public class ObjectStructure {
private List<Person> personList = new ArrayList<>();
/** * newly added * @param person */
public void add(Person person) {
personList.add(person);
}
/** * Delete * @param person */
public void delete(Person person) {
personList.remove(person);
}
/** * Traversal shows * @param scene */
public void display(Scene scene) {
personList.stream().forEach(f -> f.accept(scene));
}
}
Client class :
/** * client */
public class Client {
public static void main(String[] args) {
ObjectStructure objectStructure = new ObjectStructure();
objectStructure.add(new Young(" Xiaoshuai "));
objectStructure.add(new MiddleAged(" Lao Wang "));
// A scenario where work is not going well
WorkNotWell workNotWell = new WorkNotWell();
objectStructure.display(workNotWell);
// The scene of year-end bonus
YearEndAwards yearEndAwards = new YearEndAwards();
objectStructure.display(yearEndAwards);
// Weekend scene
Weekend weekend = new Weekend();
objectStructure.display(weekend);
}
}
Output :
Xiaoshuai : Don't stay here , I have my own place , Change jobs immediately .
Lao Wang : Bear it first , Endure again , Maybe sometimes it comes to a running day , After all, there are so many mortgage payments to be made every month .
Xiaoshuai : Buy the latest mobile phone or other electronic products , Have a good time , Today's wine is today's wine .
Lao Wang : Take it all to repay the mortgage .
Xiaoshuai : Two things , sleep , Play the game .
Lao Wang : Two things , Do housework , Bring baby .
Lao Wang said to Xiao Shuai : The visitor pattern can be applied to achieve , Without modifying the existing code , Add a new behavior to an existing class .
You see, for example, I want to add ” What time do you go to bed at night “ Scene , Just add one Sleep Class implementation Scene Interface is fine .
/** * sleep */
public class Sleep implements Scene{
@Override
public void getYoungAnswer(Young young) {
System.out.println(young.name + ": I didn't go to bed until 12:30 , verdure .");
}
@Override
public void getMiddleAgedAnswer(MiddleAged middleAged) {
System.out.println(middleAged.name + ": Go to bed at halfpastten , Early to bed and early to rise makes a man healthy,wealthy and wise. .");
}
}
And then in Client Add relevant calling code to the class , This scenario can be realized :
// Sleeping scene
Sleep sleep = new Sleep();
objectStructure.display(sleep);
Xiaoshuai : I didn't go to bed until 12:30 , verdure .
Lao Wang : Go to bed at halfpastten , Early to bed and early to rise makes a man healthy,wealthy and wise. .
You see , There is no need to modify Young and MiddleAged Class to add new operations , Isn't that amazing ?
Xiaoshuai is a little confused : It's interesting , But this code looks a little strange ,accept Method why should scene The object came in , And then put their own objects this Pass it in ?
This is not equivalent to calling other people's methods by myself , Put yourself in ?
@Override
public void accept(Scene scene) {
scene.getYoungAnswer(this);
}
Single dispatch and double dispatch
Lao Wang laughed and said :“ Take yourself in ”, Xiao Shuai, your statement is quite funny , Let me tell you something about it .
Three scenes WorkNotWell,Weekend,YearEndAwards How and Young,MiddleAged Related ?
In fact, there are two steps in the middle :
First of all , Calling display Method time , The specific scenario implementation class is passed in , Specific scenarios are identified .
second 、 stay accept Method this object , Concrete element objects (Young) It's also certain that , Then both objects are determined .
here , I also want to talk to you about order dispatch (Single Dispatch) And double dispatch (Double Dispatch) The concept of , Old Wang went on .
The so-called single dispatch , refer to Execute the method of which object , Based on the Run time type ; Which method of the execution object , According to the method parameters Compile time type .
So called double dispatch , refer to Execute the method of which object , Based on the Run time type ; Which method of the execution object , According to the method parameters Run time type .
Let's start with a piece of code :
public class Parent {
public void f() {
System.out.println(" I'm the method of the parent class f()");
}
}
public class Child extends Parent{
@Override
public void f() {
System.out.println(" I'm a subclass method f()");
}
}
/** * Single distribution */
public class SingleDispatch {
public void show(Parent p) {
p.f();
}
public void overloadFunction(Parent p) {
System.out.println(" I am a superclass parameter overloaded method :overloadFunction(Parent p)");
}
public void overloadFunction(Child c) {
System.out.println(" I am a subclass parameter overloaded method :overloadFunction(Child c)");
}
}
public class Test {
public static void main(String[] args){
SingleDispatch singleDispatch = new SingleDispatch();
Parent p = new Child();
singleDispatch.show(p);
singleDispatch.overloadFunction(p);
}
}
Output :
I'm a subclass method f()
I am a superclass parameter overloaded method :overloadFunction(Parent p)
Diagram of single dispatch :
because Java Is a single dispatch language , therefore Execute the method of which object , Based on the Run time type ,p.f() there p Running Child The object of , So the execution is Child Methods in class .



because Which method of the execution object , According to the method parameters Compile time type , The compile time type here is Parent.
So the call is public void overloadFunction(Parent p) Method .
because Java Language only supports single dispatch , So use the visitor pattern to implement double dispatch , Is that why ConcreteVisitor Class ConcreteElement Implementation class of , But can't use Element Interface .

And then through the accept Method passed in this object , To determine which method to call .
@Override
public void accept(Scene scene) {
scene.getYoungAnswer(this);
}

summary
If an object structure is complex , At the same time, the elements are stable and not easy to change , namely ConcreteElement Class is relatively stable , It will not increase at will , However, new operations need to be defined on this structure frequently , So it's very appropriate to use the visitor pattern .
advantage
- Comply with opening and closing principle , Without modifying the existing code , Add a new behavior to an existing class .
- Centralize relevant behaviors into a visitor object , Simplified element classes .
shortcoming
- Add new ConcreteElement Class is troublesome , Each new one is added ConcreteElement class , In all the Visitor Class .
If there's always something new ConcreteElement Class is added ,Vistor Class and its subclasses will become difficult to maintain , In this case, the visitor mode is appropriate .
Visitor mode makes it easier for us to add access operations , But adding elements is difficult , So the visitor pattern is suitable for structures with relatively stable elements .
边栏推荐
- Leetcode(135)——分发糖果
- Popupwindow touch event transparent transmission scheme
- Otaku can't save yuan universe
- Hosting service and SASE, enjoy the integration of network and security | phase I review
- Two fellow countrymen from Hunan have jointly launched a 10 billion yuan IPO
- Sequence stack version 1.0
- "Super point" in "Meng Hua Lu", is the goose wronged?
- 主数据建设的背景
- C语言实现扫雷(简易版)
- When querying the database with Gorm, reflect: reflect flag. mustBeAssignable using unaddressable value
猜你喜欢

图像PANR

两位湖南老乡,联手干出一个百亿IPO

Internet of things? Come and see Arduino on the cloud

Dongyuhui is not enough to bring goods to "rescue" live broadcast

Bean lifecycle flowchart

实现基于Socket自定义的redis简单客户端

微信小程序自定义tabBar

顺序栈1.0版本

Cooking business experience of young people: bloggers are busy selling classes and bringing goods, and the organization earns millions a month

Design of routing service for multi Activity Architecture Design
随机推荐
思源笔记工具栏中的按钮名称变成了 undefined,有人遇到过吗?
Wait for the victory of the party! After mining ebb tide, graphics card prices plummeted across the board
CVPR 2022缅怀孙剑!同济、阿里获最佳学生论文奖,何恺明入围
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
redis数据结构之压缩列表
Redis installation of CentOS system under Linux, adding, querying, deleting, and querying all keys
全上链哈希游戏dapp系统定制(方案设计)
[cann document express issue 06] first knowledge of tbe DSL operator development
"Ningwang" was sold and bought at the same time, and Hillhouse capital has cashed in billions by "selling high and absorbing low"
Fuzzy background of unity (take you to appreciate the hazy beauty of women)
[performance tuning basics] performance tuning strategy
年轻人捧红的做饭生意经:博主忙卖课带货,机构月入百万
maptalks:数据归一化处理与分层设色图层加载
畅直播|针对直播痛点的关键技术解析
Ribbon source code analysis @loadbalanced and loadbalancerclient
unity实战之lol技能释放范围
Agency mode -- Jiangnan leather shoes factory
Docker deploy mysql5.7
[cann document express issue 04] unveiling the development of shengteng cann operator
When querying the database with Gorm, reflect: reflect flag. mustBeAssignable using unaddressable value