当前位置:网站首页>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 .
边栏推荐
- Leetcode(135)——分发糖果
- Difference between map and object
- 【CANN文档速递05期】一文让您了解什么是算子
- [普通物理] 光栅衍射
- maptalks:数据归一化处理与分层设色图层加载
- [performance tuning basics] performance tuning standards
- CVPR 2022 remembers Sun Jian! Tongji and Ali won the best student thesis award, and hekaiming was shortlisted
- 二叉树的基本性质与遍历
- Predicate
- unity之模糊背景(带你欣赏女人的朦胧美)
猜你喜欢

"Super point" in "Meng Hua Lu", is the goose wronged?

宅男救不了元宇宙

“拯救”直播带货,一个董宇辉还不够

Basic operation of sequence table

Nodered has no return value after successfully inserting into the database (the request cannot be ended)

顺序栈1.0版本

Redis installation of CentOS system under Linux, adding, querying, deleting, and querying all keys
思源笔记工具栏中的按钮名称变成了 undefined,有人遇到过吗?

Berkeley, MIT, Cambridge, deepmind and other industry leaders' online lectures: towards safe, reliable and controllable AI

Combination mode -- stock speculation has been cut into leeks? Come and try this investment strategy!
随机推荐
16个优秀业务流程管理工具
The first public available pytorch version alphafold2 is reproduced, and Columbia University is open source openfold, with more than 1000 stars
传统的IO存在什么问题?为什么引入零拷贝的?
海泰前沿技术|隐私计算技术在医疗数据保护中的应用
二叉树的基本性质与遍历
"Ningwang" was sold and bought at the same time, and Hillhouse capital has cashed in billions by "selling high and absorbing low"
Set up your own website (14)
CVPR 2022 remembers Sun Jian! Tongji and Ali won the best student thesis award, and hekaiming was shortlisted
With its own cells as raw materials, the first 3D printing ear transplantation was successful! More complex organs can be printed in the future
消息称腾讯正式宣布成立“XR”部门,押注元宇宙;谷歌前 CEO:美国即将输掉芯片竞争,要让台积电、三星建更多工厂...
IDEA Dashboard
在Dialog中使用透明的【X】叉叉按钮图片
Leetcode(146)——LRU 缓存
Error in Android connection database query statement
Simulation lottery and probability statistics experiment of the top 16 Champions League
Leetcode(455)——分发饼干
情绪识别AI竟「心怀鬼胎」,微软决定封杀它!
Where is 5g really powerful? What is the difference with 4G?
Image panr
开放可编程基础设施(OPI)项目,重新定义DPU/IPU