In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what is the content of behavioral model". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "what is the content of the behavioral model"?
Responsibility chain model
Responsibility chain model can be divided into responsibility and chain, responsibility refers to the responsibility to do, the chain can refer to the linked list, there is a next level.
Scene: now that you are an employee of a company, you have got a more urgent document (the urgency of the document must be different), and you need a higher-level leader to deal with the document.
Ordinary mode
File class:
Public class File {private FileClass fileClass; / / the important level of the file private String content; / / the contents of the file / / omit} / / enumerated classes represent the important level of the file enum FileClass {NORMAL, IMPORTANT, EMERGENCY}
Employee Interface:
Public interface IStaff {/ / get the employee's name public String getName (); / / get the level of the file to be processed public FileClass getFileClass (); / / get the employee's demand public String getRequest ();}
Employees:
Public class Staff implements IStaff {private File file; private String name; / / omit the constructor @ Override public String getName () {return name;} @ Override public FileClass getFileClass () {return file.getFileClass ();} @ Override public String getRequest () {return "this file [" + file.getContent () + "] needs to be processed";}}
Leadership interface:
Public interface IHandler {/ / process the file public void handle (IStaff staff);}
Team leader:
Public class Leader implements IHandler {@ Override public void handle (IStaff staff) {System.out.println (staff.getName () + ":" + staff.getRequest ()); System.out.println ("team leader: deal with now");}}
Director:
Public class Director implements IHandler {@ Override public void handle (IStaff staff) {System.out.println (staff.getName () + ":" + staff.getRequest ()); System.out.println ("Director: deal with now");}}
Supervisor:
Public class Supervisor implements IHandler {@ Override public void handle (IStaff staff) {System.out.println (staff.getName () + ":" + staff.getRequest ()); System.out.println ("Supervisor: handle now");}}
Client:
Public class Client {public static void main (String [] args) {File file = new File (FileClass.IMPORTANT, "Plan"); IStaff staff = new Staff (file, "imperfect"); if (file.getFileClass (). Equals (FileClass.NORMAL)) {new Leader (). Handle (staff) } else if (file.getFileClass () .equals (FileClass.IMPORTANT)) {new Director () .handle (staff);} else if (file.getFileClass () .equals (FileClass.EMERGENCY)) {new Supervisor () .handle (staff);} else {System.out.println ("insufficient permissions");}
You see, taste carefully, this pile of if else is directly exposed in the Client class, and it is in Client that different levels are judged and dealt with by different leaders.
In a popular analogy, that is, after the employees get the documents, they all call their team leaders, directors, and supervisors to them, and then say, this document is more important, and you will have the authority to deal with it. It is true that the character can be completed, but is it realistic in this way?
What is a way to get close to reality? after employees get the documents, they first give them to their direct leader, the lowest level in the handler (chain head). Then the team leader will see if he has the responsibility to deal with the documents, and if not, he will give it to the next level to deal with it, which is the responsibility chain model.
Responsibility chain model
The file class and employee class remain unchanged, mainly due to changes in the leadership (handler).
Abstract leadership class:
Public abstract class AbstractHandler {private FileClass fileClass; private AbstractHandler nextHandler; private String name; / / the responsibilities are defined when the class is constructed / / just like you know what your responsibility is to deal with when you start the job. Public AbstractHandler (FileClass fileClass, String name) {this.fileClass = fileClass; this.name = name;} / / get the name of the leader public String getName () {return name } / / No responsibility, give it to the next level public void setNextHandler (AbstractHandler nextHandler) {this.nextHandler = nextHandler;} / / to handle the response. Everyone's response is different, so it is abstracted out of public abstract void respond (IStaff staff); / / processing information public void handle (IStaff staff) {if (fileClass.equals (staff.getFileClass () {respond (staff) } else {if (nextHandler! = null) {nextHandler.respond (staff);} else {System.out.println ("highest privilege!!") ;}
Team leader:
Public class Leader extends AbstractHandler {public Leader (String name) {super (FileClass.NORMAL, name);} @ Override public void respond (IStaff staff) {System.out.println (staff.getName () + ":" + staff.getRequest ()); System.out.println (getName () + "team leader: response");}}
Director:
Public class Director extends AbstractHandler {public Director (String name) {super (FileClass.IMPORTANT, name);} @ Override public void respond (IStaff staff) {System.out.println (staff.getName () + ":" + staff.getRequest ()); System.out.println (getName () + "Director: responded");}}
Supervisor:
Public class Supervisor extends AbstractHandler {public Supervisor (String name) {super (FileClass.EMERGENCY, name);} @ Override public void respond (IStaff staff) {System.out.println (staff.getName () + ":" + staff.getRequest ()); System.out.println (getName () + "Supervisor: responded");}}
Client:
Public class Client {public static void main (String [] args) {File file = new File (FileClass.IMPORTANT, "Marketing Plan"); IStaff staff = new Staff (file, "imperfect"); / / create leadership AbstractHandler leader = new Leader ("leaderWu"); AbstractHandler director = new Director ("directorWu"); AbstractHandler supervisor = new Supervisor ("supervisorWu") / / set the hierarchical relationship, similar to the linked list leader.setNextHandler (director); director.setNextHandler (supervisor); / / first hand to the direct leader to deal with leader.handle (staff);}} advantages and disadvantages
* * advantages: * * processing and request are separated, and employees do not know who handled the final document.
* * disadvantage: * * the disadvantage is also very obvious. If the chain of responsibility is very long and the handler happens to be at the end, do you have to go through the chain of responsibility? In this way, the performance is relatively low, and in practical use, it is generally possible to fold this maximum chain length to ensure performance.
UML class diagram
Command mode
Command mode, in a word, is to give you an order that must be obeyed and carried out, which is a bit like "obeying orders is the bounden duty of soldiers" in the army.
I don't know if the university has participated in mathematical modeling. Anyway, I have not, but I have understood the general composition. In a small team, there are generally students who are mainly responsible for search, students who write code, students who write papers and instructors.
Ordinary mode
Abstract member class (receiver):
Public abstract class NTeammate {public abstract void changeRequire (); public abstract void modify (); public abstract void work ();}
Searcher:
Public class NSearcher extends NTeammate {@ Override public void changeRequire () {System.out.println ("searcher is aware of the change in requirements");} @ Override public void modify () {} @ Override public void work () {System.out.println ("searcher starts searching for relevant information");}}
Writer:
Public class NWriter extends NTeammate {@ Override public void changeRequire () {System.out.println ("writer learned about the change in requirements");} @ Override public void modify () {System.out.println ("writer revision paper");} @ Override public void work () {System.out.println ("writer starts writing the paper");}}
Coder:
Public class NCoder extends NTeammate {@ Override public void changeRequire () {System.out.println ("coder learned about the requirement change");} @ Override public void modify () {System.out.println ("coder modification code");} @ Override public void work () {System.out.println ("coder start code");}}
Teacher:
Public class NTeacher {public static void main (String [] args) {NTeammate writer = new NWriter (); / / need to change the article writer.modify (); writer.work ();}}
At first, the teacher saw that the exhibition was not concise enough, so he called writer and asked him to modify it, so he had the Teacher class above. In fact, this is good, because the article, just modify and polish it.
After a day, the teacher looked carefully and found that the algorithm of the code has bug. This loophole led not only to coder to modify the code, but also to writer to modify the corresponding articles.
Now the teacher has to contact not only writer but also coder, so how should the Teacher class be modified?
Public class NTeacher {public static void main (String [] args) {NTeammate writer = new NWriter (); NTeammate coder = new NCoder (); / / need to change bug and the article writer.modify (); writer.work (); coder.modify (); coder.work ();}}
It can be found that there is one more requirement, and the code has been greatly changed than before, which we do not want to see. Some partners may want to use the intermediary model, but the intermediary pattern is to reduce the coupling between classes, and the searcher,writer,coder in this example is not coupled and does its own job.
Command mode
If only there was an Invoker in the team, we could communicate with the teacher (client). Not only that, the teacher's instructions must be of String type. We can encapsulate the instructions into a class (command). The captain only needs to issue orders to instruct the team members (receiver) what to do. This is the command mode, and the team must do what the order requires.
Abstract team members and specific team members are still the same as above, so I won't repeat them here.
Abstract command class:
Public abstract class AbstractCommand {protected Coder coder = new Coder (); protected Searcher searcher = new Searcher (); protected Writer writer = new Writer (); / / there must be a method to execute, issue a command public abstract void execute ();}
Specific command class (Command):
Any commands can be encapsulated.
Change requirements:
Public class ChangeInfoCommand extends AbstractCommand {@ Override public void execute () {searcher.changeRequire (); writer.changeRequire (); coder.changeRequire ();}}
Modify the article:
Public class ModifyArticleCommand extends AbstractCommand {@ Override public void execute () {writer.modify (); writer.work ();}}
Modify the code:
Public class ModifyCodeCommand extends AbstractCommand {@ Override public void execute () {coder.modify (); coder.work (); writer.modify (); writer.work ();}}
Captain class (Invoke):
Public class Captain {/ / contact the command AbstractCommand abstractCommand; public Captain (AbstractCommand abstractCommand) {this.abstractCommand = abstractCommand;} public void invoke () {/ / issue the command to require the team to take the corresponding action abstractCommand.execute ();}}
Teacher class (Client):
Public class Teacher {public static void main (String [] args) {AbstractCommand command = new ModifyCodeCommand (); Captain captain = new Captain (command); captain.invoke ();}}
If the teacher feels bad again, what to do? there is no need to practice with the members, just put forward another suggestion, and the captain should not practice with the team members, just issue orders and instruct the team members to do it. Modification is as simple as that, one line of code.
Public class Teacher {public static void main (String [] args) {/ / AbstractCommand command = new ModifyCodeCommand (); AbstractCommand command = new ModifyArticleCommand (); Captain captain = new Captain (command); captain.invoke ();}} extension
If, ah, when you change the code, you not only need to modify bug and modify articles, but also need searcher to collect information, what should I do?
Public class ModifyCodeCommand extends AbstractCommand {@ Override public void execute () {searcher.work (); / / you only need to add it to the specific command. The client is completely unknown to coder.modify (); coder.work (); writer.modify (); writer.work ();}}
Another situation is that after some changes, the teacher finds that the previous version is better, which requires each team member to have a callback function to undo the action and return to the previous state, that is, to find the saved previous version of the file. You only need to add a callback function to the abstract receiver class:
Public abstract class NTeammate {public abstract void changeRequire (); public abstract void modify (); public abstract void work (); / / specific teammates are implementing the callback method public abstract void rollback ();} in their own way.
Then add a recall command
Public class callBackCommand extends AbstractCommand {@ Override public void execute () {/ / of course, who needs to withdraw is searcher.rollback (); writer.rollback (); coder.rollback ();}} UML class diagram
Interpreter mode
This is a relatively unpopular design pattern both at work and in study. The interpreter pattern consists of the following classes
Context: Context is used to encapsulate the global information of the interpreter. All specific interpreters need to access Context.
AbstractExpression: an abstract class or interface that declares the interpretation method executed and is implemented by all specific interpreters
TerminalExpression: an interpreter class that implements operations related to syntax terminators. The Terminator expression must be implemented and instantiated because it represents the end of the expression.
NonTerminalExpreesion: this is a class that implements different rules or symbols for syntax. A class should be created for each syntax.
The explanation of this thing is rather mouthful, and there is no good popular explanation for the time being, so let's just look at the example.
AbstractExpressionpublic interface Expression {public float interpret ();} TerminalExpressionpublic class Number implements Expression {private final float number; public Number (float number) {this.number = number;} @ Override public float interpret () {return number;}}
Remember the flow we talked about before, TerminalExpression is like a terminal operation, and NonTerminalExpression is similar to an intermediate operation.
NonTerminalExpressionpublic class Plus implements Expression {Expression left; Expression right; public Plus (Expression left, Expression right) {this.left = left; this.right = right;} @ Override public float interpret () {return left.interpret () + right.interpret ();}}
Note that there should be a separate class for each syntax
Public class Minus implements Expression {Expression left; Expression right; public Minus (Expression left, Expression right) {this.left = left; this.right = right;} @ Override public float interpret () {return left.interpret ()-right.interpret ();}} Contextpublic class Evaluator {public static void main (String [] args) {Evaluator evaluator = new Evaluator () System.out.println (evaluator.evaluate ("34 +")); System.out.println (evaluator.evaluate ("43 -")); System.out.println (evaluator.evaluate ("43-2 +"));} public float evaluate (String expression) {Stack stack = new Stack (); float result = 0 For (String token: expression.split ("")) {Expression exp = null; if (isOperator (token)) {if (token.equals ("+")) {exp = stack.push (new Plus (stack.pop (), stack.pop () } else if (token.equals ("-")) {exp = stack.push (new Minus (stack.pop (), stack.pop ();} if (null! = exp) {result = exp.interpret (); stack.push (new Number (result)) }} if (isNumber (token)) {stack.push (new Number (Float.parseFloat (token));}} return result;} private boolean isNumber (String token) {try {Float.parseFloat (token); return true } catch (NumberFormatException e) {return false;}} private boolean isOperator (String token) {return token.equals ("+") | | token.equals ("-");}} UML class diagram
At this point, I believe you have a deeper understanding of "what is the content of the behavioral model?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.