当前位置:网站首页>Memo mode - game archiving
Memo mode - game archiving
2022-06-24 20:35:00 【zhanyd】
List of articles
Introduction
Xiaoshuai works in a game company . Recently, the leader asked him to design the automatic archiving function of the game , Every time a player challenges boss When , The system shall be able to realize automatic archiving . If the player fails the challenge ,game over 了 , You can return to the state before the challenge and do it again .
Shuai thought , I use a backup object to record all the game parameters , When the player wants to read the archive , Just restore the data in the backup object ?
Common method
Xiaoshuai quickly wrote the code :
/** * Heroes */
public class Hero {
/** * Health value */
private int healthPoint;
/** * Magic value */
private int magicalValue;
/** * aggressivity */
private int attackPower;
public Hero(int healthPoint, int magicalValue, int attackPower) {
this.healthPoint = healthPoint;
this.magicalValue = magicalValue;
this.attackPower = attackPower;
}
/** * Game over */
public void gameOver() {
this.healthPoint = 0;
this.magicalValue = 0;
this.attackPower = 0;
}
/** * Set properties * @param healthPoint * @param magicalValue * @param attackPower */
public void setState(int healthPoint, int magicalValue, int attackPower) {
this.healthPoint = healthPoint;
this.magicalValue = magicalValue;
this.attackPower = attackPower;
}
@Override
public String toString() {
StringBuffer display = new StringBuffer();
display.append(" Health value :" + this.healthPoint + "\n");
display.append(" Magic value :" + this.magicalValue + "\n");
display.append(" aggressivity :" + this.attackPower + "\n");
return display.toString();
}
public int getHealthPoint() {
return healthPoint;
}
public void setHealthPoint(int healthPoint) {
this.healthPoint = healthPoint;
}
public int getMagicalValue() {
return magicalValue;
}
public void setMagicalValue(int magicalValue) {
this.magicalValue = magicalValue;
}
public int getAttackPower() {
return attackPower;
}
public void setAttackPower(int attackPower) {
this.attackPower = attackPower;
}
}
/** * Client class */
public class Client {
public static void main(String[] args) {
Hero hero = new Hero(90,85,70);
// Challenge boss The state before
System.out.println(" Challenge boss The state before :\n" + hero);
// Save progress
Hero heroBackUp = new Hero(hero.getHealthPoint(), hero.getMagicalValue(), hero.getAttackPower());
// Challenge failure
hero.gameOver();
System.out.println(" The state after the challenge fails :\n" + hero);
// Recovery schedule
hero.setState(heroBackUp.getHealthPoint(), heroBackUp.getMagicalValue(), heroBackUp.getAttackPower());
System.out.println(" The status after the progress is restored :\n" + hero);
}
}
Output :
Challenge boss The state before :
Health value :90
Magic value :85
aggressivity :70
The state after the challenge fails :
Health value :0
Magic value :0
aggressivity :0
The status after the progress is restored :
Health value :90
Magic value :85
aggressivity :70
Xiaoshuai thinks this is not very simple ?
I just need to build another one heroBackUp object , hold hero The state of the object is saved , Wait until you need to read the file heroBackUp The state in the object is OK ?
At this time, Lao Wang in the project team spoke :
You use it directly Hero Class as a backup , Convenience is convenience , But it's not safe ,Hero Class has attributes that are public set Method . Backup heroBackUp object , It may be called by others set Method to change properties .
The backup object is read-only , Cannot be modified .

heroBackUp Objects may be modified by other objects , This violates the encapsulation principle .
So how can we do this without violating the encapsulation principle , Back up an object ? Xiao Shuai hurriedly asked .
Lao Wang smiles : This requires the memo mode .
Memo mode
Memo mode : Without violating the encapsulation principle , Capture the internal state of an object , And save the state outside the object . In this way, the object can be restored to the original saved state later .
Memo pattern is a behavior design pattern , Allows you to save and restore an object's previous state without exposing its implementation details .

- Memento( Memorandum ): The memo stores the internal state of the originator object ; The internal state of the memo can only be accessed by the originator .
- Originator( Primary device ): Create a memo , Record the current state ; Use memo to restore state .
- Caretaker( person in charge ): Management memo ; The contents of the memo cannot be operated or checked .
Lao Wang transformed the code before long :
Originator class :
/** * Heroes ( Namely Originator) */
public class Hero {
/** * Health value */
private int healthPoint;
/** * Magic value */
private int magicalValue;
/** * aggressivity */
private int attackPower;
public Hero(int healthPoint, int magicalValue, int attackPower) {
this.healthPoint = healthPoint;
this.magicalValue = magicalValue;
this.attackPower = attackPower;
}
/** * Game over */
public void gameOver() {
this.healthPoint = 0;
this.magicalValue = 0;
this.attackPower = 0;
}
/** * Create a memo * @return */
public Memento createMemento() {
return new Memento(healthPoint, magicalValue, attackPower);
}
/** * Recover data from memo * @param memento */
public void restoreMemento(Memento memento) {
this.healthPoint = memento.getHealthPoint();
this.magicalValue = memento.getMagicalValue();
this.attackPower = memento.getAttackPower();
}
@Override
public String toString() {
StringBuffer display = new StringBuffer();
display.append(" Health value :" + this.healthPoint + "\n");
display.append(" Magic value :" + this.magicalValue + "\n");
display.append(" aggressivity :" + this.attackPower + "\n");
return display.toString();
}
}
Memento :
/** * Memorandum class */
public class Memento {
/** * Health value */
private int healthPoint;
/** * Magic value */
private int magicalValue;
/** * aggressivity */
private int attackPower;
public Memento(int healthPoint, int magicalValue, int attackPower) {
this.healthPoint = healthPoint;
this.magicalValue = magicalValue;
this.attackPower = attackPower;
}
/** * In the memo only get Method , No, set Method , Because the data in the memo should not be modified * @return */
public int getHealthPoint() {
return healthPoint;
}
/** * In the memo only get Method , No, set Method , Because the data in the memo should not be modified * @return */
public int getMagicalValue() {
return magicalValue;
}
/** * In the memo only get Method , No, set Method , Because the data in the memo should not be modified * @return */
public int getAttackPower() {
return attackPower;
}
}
Caretaker:
/** * Responsible for human */
public class Caretaker {
/** * Memorandum */
private Memento memento;
public Memento getMemento() {
return memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
Client :
/** * Client class */
public class Client {
public static void main(String[] args) {
Hero hero = new Hero(90,85,70);
// Challenge boss The state before
System.out.println(" Challenge boss The state before :\n" + hero);
// Save progress
Caretaker caretaker = new Caretaker();
caretaker.setMemento(hero.createMemento());
// Challenge failure
hero.gameOver();
System.out.println(" The state after the challenge fails :\n" + hero);
// Recovery schedule
hero.restoreMemento(caretaker.getMemento());
System.out.println(" The status after the progress is restored :\n" + hero);
}
}
Output :
Challenge boss The state before :
Health value :90
Magic value :85
aggressivity :70
The state after the challenge fails :
Health value :0
Magic value :0
aggressivity :0
The status after the progress is restored :
Health value :90
Magic value :85
aggressivity :70
I define a separate class (Memento class ) To represent backup , Not reuse Hero class . This class only exposes get() Method , No, set() Any method to modify the internal state . This ensures that the data will not be modified , Conform to the packaging principle .
Caretaker Class is responsible for managing Memento class , however Caretaker Class to Memento Class has limited permissions , Do not modify Memento Class .
Lao Wang concluded .
Implementation of revocation function
Old Wang went on : If we want to implement the common Undo function , Can be in Caretaker In class Stack To store Memento object .
Every time you perform an operation, you call Stack Of push() How to put a Memento Objects on the stack .
Call when undoing Stack Of pop() Way out of the stack , Take out a Memento object , To recover .
Xiaoshuai couldn't help admiring : You are much better than Lao Wang next door !
summary
When you need to create a snapshot of an object's state to restore its previous state , You can use memo mode .
This pattern suggests that a copy of the object state be stored in a named memo (Memento) In a special object . Memos let objects take responsibility for creating snapshots of their state , In addition to the object that created the memo , No other object can access the contents of the memo .
Caretaker Objects must interact with memos using restricted interfaces , It can get Memento Object itself , But it can't get and change Memento Property state in the object .
advantage
- It is possible to maintain the encapsulated state , Create a memo about the state of the object , Ensure the security of memo data .
- This can be done by having the person in charge maintain the memo , To simplify the generator code .
shortcoming
- If the client creates memos too often , The program will consume a lot of memory .
边栏推荐
猜你喜欢

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

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

Freshman girls' nonsense programming is popular! Those who understand programming are tied with Q after reading

物聯網?快來看 Arduino 上雲啦

使用gorm查询数据库时reflect: reflect.flag.mustBeAssignable using unaddressable value

Leetcode (135) - distribute candy

年轻人捧红的做饭生意经:博主忙卖课带货,机构月入百万

Sequence stack version 1.0
![[performance tuning basics] performance tuning strategy](/img/83/be41a6a0c5c186d3fb3a120043c53f.jpg)
[performance tuning basics] performance tuning strategy

16个优秀业务流程管理工具
随机推荐
Error in Android connection database query statement
Basic operation of sequence table
实现基于Socket自定义的redis简单客户端
Camera rental management system based on qt+mysql
Get to know the data structure of redis - hash
Introduction: continuously update the self-study version of the learning manual for junior test development engineers
First understand redis' data structure - string
Set up your own website (14)
Implement the redis simple client customized based on socket
Internet of things? Come and see Arduino on the cloud
JVM tuning
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
年轻人捧红的做饭生意经:博主忙卖课带货,机构月入百万
gateway
The AI for emotion recognition was "harbouring evil intentions", and Microsoft decided to block it!
How does the video platform import the old database into the new database?
unity之模糊背景(带你欣赏女人的朦胧美)
在Dialog中使用透明的【X】叉叉按钮图片
Grating diffraction
基于QT+MySQL的相机租赁管理系统