In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how to use behavioral mode". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
State mode
The advantage of the state mode is that it localizes the behavior related to a particular state and separates the behavior of different states.
Put specific related behaviors into one object, and since all state-related code exists in a ConcreteState, you can easily add new states and transitions by defining new subclasses.
Context: context that defines the interface required by the client and maintains a state class.
State: a state class that defines an interface to encapsulate a specific state-related behavior of the context, and state-related operations are delegated to specific state objects for processing.
Concrete State: concrete status class
State mode UML
The example used is within the Masters, either in the group or on the way, which involves the change of state.
State mode
State
Public interface State {void handle (Context context);}
Concrete State
State of returning to the city
Public class ConcreteStateBack implements State {@ Override public void handle (Context context) {System.out.println ("No status, go back to the city to make up a status first"); context.setState (new ConcreteStateWalk ());}}
Group-playing state
Public class ConcreteStateFight implements State {@ Override public void handle (Context context) {System.out.println ("push the big move, open the sky, put your hands, either black screen or kill five"); context.setState (new ConcreteStateBack ());}}
The state of the road when playing a group.
Public class ConcreteStateWalk implements State {@ Override public void handle (Context context) {System.out.println ("status is full, wait for me to gather and form a group"); context.setState (new ConcreteStateFight ());}}
Failure state
Public class ConcreteStateDefeated implements State {@ Override public void handle (Context context) {System.out.println ("Defeited subscription!");}}
Context
Public class Context {private State state; public State getState () {return state;} public void setState (State state) {this.state = state;} public Context (State state) {this.state = state;} public void request () {state.handle (this);}}
Client
Public class Client {public static void main (String [] args) {Context context = new Context (new ConcreteStateWalk ()); for (int I = 0; I
< 8; i++) { context.request(); } context.setState(new ConcreteStateDefeated()); context.request(); }}策略模式 策略模式是一种定义一系列算法的方法,但是这些方法最终完成的都是相同的工作,只是策略不同,也就是实现不同。 它可以以相同的方式来调用所有的算法,减少了各种算法类和使用算法类之间的耦合。 Context: 上下文,内部有个strategy属性,并且能够通过其调用策略 Strategy: 策略接口或者抽象类,定义了策略的方法 Concrete Strategy: 具体的策略 状态模式UML 状态模式 还是拿游戏举例,最终的目的都是为了赢,但是具体的方式可能要根据对方的阵容做出改变。Context
Public class Context {Strategy strategy; public Context (Strategy strategy) {this.strategy = strategy;} public void invokeStrategy () {strategy.play ();}}
Strategy
Public interface Strategy {void play ();}
Concrete Strategy
Public class ConcreteStrategyAttackMid implements Strategy {@ Override public void play () {System.out.println ("assemble attack center");}} public class ConcreteStrategyGank implements Strategy {@ Override public void play () {System.out.println ("turn the line to catch people and push towers");}} public class ConcreteStrategyInvade implements Strategy {@ Override public void play () {System.out.println ("invading wild areas");}}
Client
Public class Client {public static void main (String [] args) {Context context = new Context (new ConcreteStrategyAttackMid ()); context.invokeStrategy (); context = new Context (new ConcreteStrategyGank ()); context.invokeStrategy (); context = new Context (new ConcreteStrategyInvade ()); context.invokeStrategy ();}} template method mode
The template method is to define the skeleton of an operational algorithm and defer some steps to subcategories. The template method enables the subclass to redefine some specific steps of the modified algorithm without changing the structure of an algorithm.
In short, I'll give you a template, what the steps are, but how to implement it depends on the individual.
Abstract Class: implements a template method that defines the estimation of the algorithm
Concrete Class: different implementations of each algorithm in the template
Template method UML
Template method
We all know that the assembly of computers has a template, which parts are fixed, the difference is that the use of parts is different. In this way, we can encapsulate the assembly as a behavior template.
Abstract Class
Public abstract class AbstractClass {public void assemble () {System.out.println ("start template assembly computer"); cpu (); radiating (); screen ();} public abstract void cpu (); public abstract void radiating (); public abstract void screen ();}
Concrete Class
Public class ConcreteClassMid extends AbstractClass {@ Override public void cpu () {System.out.println ("Intel 10900K, the occasional god of Intel");} @ Override public void radiating () {System.out.println ("double copper heat sink");} @ Override public void screen () {System.out.println ("75hz high quality screen");}}
Public class ConcreteClassTop extends AbstractClass {@ Override public void cpu () {System.out.println ("eternal god of AMD5950X,AMD");} @ Override public void radiating () {System.out.println ("double copper radiator tubes with liquid cooling");} @ Override public void screen () {System.out.println ("144hz electronic competition screen");}}
Client
Public class Client {public static void main (String [] args) {AbstractClass templateToAssembleComputer = new ConcreteClassMid (); templateToAssembleComputer.assemble (); templateToAssembleComputer = new ConcreteClassTop (); templateToAssembleComputer.assemble ();}}
Do you have any impression that the builder pattern mentioned before can be said to be very similar, because the builder pattern is realized with the help of the template method pattern.
Memo mode
Without breaking the encapsulation, capture the internal state of an object and save that state outside the object, so that the object can be restored to its previously saved state later. The memo is also more vivid, just like when we solve a problem, we can write down the process, and finally we can check it step by step, know what went wrong, and resume the problem-solving process from there, so as to solve the problem correctly.
Originator: the initiator is the object we need to remember the state to restore at some point.
Caretaker: the manager is the class responsible for triggering the initiator's change or triggering the initiator to return to the previous state action.
Memento: a memo is a class responsible for storing the initiator's internal state. Memos provide ways to set and get status, but these methods should be hidden from managers.
* * scene: * * everyone has played games like Super Mary, Alloy warheads, or I wanna. What is the composition, one is the player (Originator), one is the file that often needs to be archived (Memento), and the other is the game background management (Caretaker).
For players, you can archive (setMemento and createMemento), or you can read the file and restore it to the last archived location (restoreMemento).
Memo UML
Normal memo mode:
Originator (player)
Public class OriginatorPlayer {private String name; private String status; public OriginatorPlayer (String name) {this.name = name;} / / give the game backend processing 1 public MementoGameState create () {return new MementoGameState (status);} / / player Archive 2 public void save (String status) {this.status = status; System.out.println ("Archive:" + status) } public void read (MementoGameState gameState) {this.status = gameState.getGameStatus (); System.out.println ("read file:" + status);}}
In fact, I think the first two steps can be written together like this.
Public MementoGameState save (String status) {this.status = status; System.out.println ("Archive:" + status); return new MementoGameState (status);}
Memento (game status)
Public class MementoGameState {private String gameStatus = ""; public MementoGameState (String gameStatus) {this.gameStatus = gameStatus;} public String getGameStatus () {return gameStatus;}}
Caretaker (background Management)
Public class CaretakerGameManager {MementoGameState gameState; public MementoGameState getGameState () {return gameState;} / / this is the real backend archive public void setGameState (MementoGameState gameState) {System.out.println ("system archived:" + gameState.getGameStatus ()); this.gameState = gameState;}}
Client
Public class Client {public static void main (String [] args) {OriginatorPlayer cutey = new OriginatorPlayer ("cutey"); CaretakerGameManager gameManager = new CaretakerGameManager (); / / the player clicks the archive, but the cutey.save may not be saved successfully ("first pass"); / / the backend needs to process the player's archive request (imperfect.create ()) gameManager.setGameState (cutey.create ()) Cutey.save ("second pass"); gameManager.setGameState (cutey.create ()); / / in this case, it is possible that we clicked on the archive and quit cutey.save ("third pass") without success; / / read the file cutey.read (gameManager.getGameState ());}}
If you look at the code carefully, you will find that, in the final analysis, the memo is not the state of the game character, so there is a special GameState to store this state.
When the state is restored, the state in the read memo is assigned to the game character. So it all boils down to how to save the game character's state and then restore it when needed.
Is it necessary to create a new class to save it for us? if we directly save the last stage of the game character (rather than the simple game state), and then read the last stage of the game character directly when reading the file?
It is certainly possible that the sponsor (Originator) also acts as a Memento.
Again, I want to save myself, and I want to copy myself as a memo. In order to save space, I will use the prototype model that I will talk about later.
At this point, the ordinary memo model has been talked about, the following are based on ordinary improvements, but do not look at it.
Clone-based memo model:
Players:
Public class PlayerC implements Cloneable {private String name; private String state; public PlayerC (String name) {this.name = name;} public String getState () {return state;} public void setState (String state) {System.out.println ("player to:" + state); this.state = state } / / archive, save your own public PlayerC create () {System.out.println ("player Archives:" + this.clone (). GetState ()); return this.clone ();} / / read file public void play (PlayerC playerC) {System.out.println ("player read:" + playerC.getState ()); setState (playerC.getState () } / / clone yourself @ Override public PlayerC clone () {try {return (PlayerC) super.clone ();} catch (CloneNotSupportedException e) {e.printStackTrace ();} return null;}}
Background management:
Public class GameManagerC {PlayerC playerC; public PlayerC getPlayerC () {return playerC;} / / Real archived public void setPlayerC (PlayerC playerC) {this.playerC = playerC;}}
Client:
Public class ClientC {public static void main (String [] args) throws CloneNotSupportedException {PlayerC playerC = new PlayerC ("perfext"); GameManagerC gameManagerC = new GameManagerC (); / / Analysis is the same as normal mode, so no more playerC.setState (""); gameManagerC.setPlayerC (playerC.create ()); playerC.setState ("% 20"); gameManagerC.setPlayerC (playerC.create ()) PlayerC.setState ("30"); playerC.play (gameManagerC.getPlayerC ());}}
The above is not even the most concise, because in fact, we still have to save in the background management class, of course, this is what we would like to see. Think about what the role of the background management class is, it is used to manage memos. Since memos can be omitted, background management classes can naturally be simplified.
In other words, the player's state is kept inside the player, but this is not consistent with the definition. At the beginning, I specially bold "save this state outside the object". So this blog no longer talks about the implementation of this approach, and it is relatively simple (hint: declare a member variable as a restored game character within the player class).
All of the above are relatively simple memo modes, and there are two more commonly used ones, one is that a character has multiple states and needs to be remembered at the same time, first talk about this, and the other is related.
Multi-state memo mode:
Scene: a character has multiple states, which is still an example of playing a game, but the game character is not just a few levels. The new characters have, at what stage, what level, and equipped with three states.
Players:
Public class PlayerS {private String name; private String equipment; private String schedule; private String grade; / / Archive public GameStateS save () {System.out.println ("player Archives:" + toString ()); return new GameStateS (this) } / / read the file one by one from the saved state: public void read (GameStateS gameStateS) {equipment = (String) gameStateS.getStates (). Get ("equipment"); schedule = (String) gameStateS.getStates (). Get ("schedule"); grade = (String) gameStateS.getStates (). Get ("grade"); System.out.println ("player readings:" + toString ()) } public PlayerS (String name) {this.name = name;} / * * omit * 1.toString method to facilitate printing * 2.set method, convenient for players to archive * 3.get method, convenient to store player's status * /}
Game status (file):
Public class GameStateS {/ / multi-state, so use hashmap to save private HashMap states = new HashMap (); / / save the player's state public GameStateS (PlayerS playerS) {states.put ("schedule", playerS.getSchedule ()); states.put ("grade", playerS.getGrade ()); states.put ("equipment", playerS.getEquipment ());} public HashMap getStates () {return states;}}
Background management:
Public class GameManagerS {private GameStateS gameStateS; public GameStateS getGameStateS () {return gameStateS;} / / actual archiving public void setGameStateS (GameStateS gameStateS) {System.out.println ("system archived!"); this.gameStateS = gameStateS;}}
Client:
Public class ClientS {public static void main (String [] args) {PlayerS player = new PlayerS ("perfext"); GameManagerS gameManagerS = new GameManagerS (); player.setSchedule ("10%"); player.setEquipment ("2-piece set"); player.setGrade ("level 6"); gameManagerS.setGameStateS (player.save ()); player.setSchedule ("30%"); player.setEquipment ("4-piece set") Player.setGrade ("level 10"); gameManagerS.setGameStateS (player.save ()); player.setSchedule ("80%"); player.setEquipment ("6-piece set"); player.setGrade ("level 15"); System.out.println ("forgot to archive!" Already hit: "); System.out.println (player.toString ()); player.read (gameManagerS.getGameStateS ());}}
The essence is still the same, without much change, that is, the state is encapsulated in hashmap.
So far, for all the memo modes mentioned above, I don't know if you have found a problem, that is, when you recover, you can only restore a specific state (usually the last memo).
But in the real world, you can always ctrl + z (undo) several times when you code or type code, and you can undo it back to satisfaction. What I'm going to talk about next should help you.
Cancel the memo mode multiple times:
Forgive me for not knowing how to express this memo mode in a high-end and professional way.
* * scene: * * the words spoken in the game are not very clear, then the typist (Originator) types, and the content (Memento) is saved by the computer (Caretaker) to demonstrate.
Typist:
Public class Typist {private String name; private String word; / / the latest state private List content = new ArrayList (); / / the position of all states int len = 0; / / the location of the state to read public Typist (String name) {this.name = name;} public void setWord (String word) {this.word = word } / / Save public TypeContent save () {content.add (word); System.out.println ("typist Save:" + word); len++; / / length + 1 return new TypeContent (content);} / / read public void read (TypeContent typeContent) {content = typeContent.getTypeContent () System.out.println ("currently shown:" + content.get (--len)); / / length after reading-1}}
Content:
Public class TypeContent {private List typeContent = new ArrayList (); / / Save the user-written word public TypeContent (List typeContent) {this.typeContent = typeContent;} public List getTypeContent () {return typeContent;}}
Computer:
Public class Computer {private TypeContent typeContent; public TypeContent getTypeContent () {return typeContent;} / / actually save the user-written word public void setTypeContent (TypeContent typeContent) {this.typeContent = typeContent;}}
Client:
Public class ClientM {public static void main (String [] args) {Typist perfext = new Typist ("perfext"); Computer computer = new Computer (); perfext.setWord ("abcd"); computer.setTypeContent (perfext.save ()); perfext.setWord ("efg"); computer.setTypeContent (perfext.save ()); perfext.setWord ("hijkl"); computer.setTypeContent (perfext.save ()) Perfext.setWord ("mnopq"); computer.setTypeContent (perfext.save ()); perfext.read (computer.getTypeContent ()); / / simulated ctrl+z System.out.println ("undo:"); perfext.read (computer.getTypeContent ()); System.out.println ("undo:"); perfext.read (computer.getTypeContent ()) That's all for System.out.println ("undo:"); perfext.read (computer.getTypeContent ());}} "how to use Behavioral patterns". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.