当前位置:网站首页>Memo mode - unity
Memo mode - unity
2022-07-27 22:10:00 【Just be interesting】
List of articles
Memo mode
Memo mode is object behavior mode , Also known as snapshot mode , Without breaking encapsulation , Capture an object state and save , And when you need it , To restore .
In many games , We all have archiving function , Save the state during the archiving process . There are also many software with undo function , In addition to the storage of commands , And save the current state .
It is not difficult to save the state , But we need to protect the fields of the saved object , You can also save it . This is the black box .
Use here Double interface To complete the access to different classes .
Double interface
- Narrow interface : Objects other than the initiator are obtained through narrow interfaces , This interface can only transfer objects , Cannot modify object .
- Wide interface : Unlike narrow interfaces , The wide interface can access all the information in the object , Allow reading .
structure 
explain
- Primary device (Originator) - Protect your state , And you can generate memo classes through snapshots to save your own state , You can also restore your state through snapshots .
- Memorandum (Memento) - An immutable value object ( read-only ), Create new objects through construction . Save a snapshot .
- person in charge (Caretaker)- Be responsible for recording snapshots , And keep , Send a snapshot to the initiator to restore the state when necessary , You can manage snapshots , But it can't be modified .
- Narrow interface (I Memento) - As identifier , There's no way , The person in charge through the narrow interface ( black box ) To deliver .
Realization
The function of saving game archives
It uses SteamAssets Folder
Player information ( Primary device ) and Memorandum ( nesting )
public class PlayerInfo : MonoBehaviour
{
private FileSave _save;
[SerializeField] private string _name;
[SerializeField] private int _grade;
[SerializeField] private int _attackForce;
[SerializeField] private float _hp;
private void Awake()
{
_save = new FileSave();
}
// The person in charge only works with serialized Json Dealing with strings
public void Save()
{
PlayerStateMemento memento =
new PlayerStateMemento(_name, _grade, _attackForce, _hp);
string json = JsonUtility.ToJson(memento, true);
_save.Save(json);
}
public void Restore()
{
string json = _save.ReadArchive();
PlayerStateMemento memento =
JsonUtility.FromJson<PlayerStateMemento>(json);
_name = memento.Name;
_grade = memento.Grade;
_attackForce = memento.AttackForce;
_hp = memento.Hp;
}
// Immutable type , read-only
[Serializable]
private class PlayerStateMemento
{
[SerializeField] private string _name;
[SerializeField] private int _grade;
[SerializeField] private int _attackForce;
[SerializeField] private float _hp;
public string Name => _name;
public int Grade => _grade;
public int AttackForce => _attackForce;
public float Hp => _hp;
public PlayerStateMemento(string name, int grade, int attackForce, float hp)
{
_name = name;
_grade = grade;
_attackForce = attackForce;
_hp = hp;
}
}
}
File saving class ( person in charge )
public class FileSave
{
private string _path;
public FileSave()
{
CreateSaveFile();
}
public void Save(string json)
{
File.WriteAllText(_path, json);
}
public string ReadArchive()
{
return File.ReadAllText(_path);
}
private void CreateSaveFile()
{
if (!string.IsNullOrEmpty(_path)) return;
_path = Application.streamingAssetsPath;
if (!Directory.Exists(_path))
Directory.CreateDirectory(_path);
_path = Path.Combine(_path, "Save.json");
if (!File.Exists(_path))
File.Create(_path);
}
}
Test with two buttons 

Successful file reading , Here are Json file
Application scenarios
- When you need to record the state of an object , And hope to restore the previous state .
- When you need to obtain different access permissions through dual interfaces
Advantages and disadvantages
advantage
- Without destroying the encapsulation , Create a snapshot of object state
- Snapshots can be maintained , To restore the previous state
shortcoming - Create snapshots too often , It may consume a lot of memory
Relationship with other models
- Use both command mode and memo mode to realize revoke The function of , under these circumstances , Commands are used for the operation of objects , The memo is used to restore the previous state .
In languages that do not support nested classes
We can use two interfaces to realize double interface operation
边栏推荐
- day 1 - day 4
- 每条你收藏的资讯背后,都离不开TA
- STM32项目分享---MQTT智能门禁系统(含APP控制)
- Can JVM tuning be done with single core CPU and 1G memory?
- After sorting (bubble sorting), learn to continuously update other sorting methods
- 云原生微服务第三章之Haproxy+Keepalived
- Are Transformers Effective for Time Series Forecasting?|填坑
- [stonedb fault diagnosis] MDL lock waiting
- Is log4j vulnerability still widespread?
- 零钱通项目(两个版本)含思路详解
猜你喜欢

JVM garbage collection garbage collector and common combination parameters

How long will it take to learn the four redis cluster solutions? I'll finish it for you in one breath
![Tencent cloud [hiflow] | automation --------- hiflow: still copying and pasting?](/img/dd/8ee989f5c9db632f78e79425497e71.png)
Tencent cloud [hiflow] | automation --------- hiflow: still copying and pasting?

Inventory Poka ecological potential project | cross chain characteristics to promote the prosperity of multi track

2022 2nd cyber edge cup cyber security competition Web

Why do server programs need to listen first

零钱通项目(两个版本)含思路详解

matlab 绘制三坐标(轴)图

day 1 - day 4

An2021软件安装及基本操作(新建文件/导出)
随机推荐
B站崩了,那晚负责修复的开发人员做了什么?
云原生微服务第三章之Haproxy+Keepalived
Log4j 漏洞仍普遍存在,并持续造成影响
It seems to be a bug of thread pool, but I think the source code design is unreasonable.
Enumeration and annotation
二维数组的基本用法
Technology Management - we must focus on the big and let go of the small
What is modcount in the source code? What's the effect
Learn the use principle and core idea of thread pool from the source code
How to use Fiddler for weak network testing
Shengyang technology officially launched the remote voiceprint health return visit service system!
项目分析(从技术到项目、产品)
MySQL series - database tables, queries, sorting, and data processing functions
matlab 绘制三坐标(轴)图
Deepfake's face is hard to distinguish between true and false, and musk Fenke has disguised successfully
Interview question: talk about your understanding of AQS
Live broadcast software app development, uniapp scroll view hidden scroll bar
Understanding of L1 regularization and L2 regularization [easy to understand]
Station B collapsed. If we were the developer responsible for the repair that night
Is log4j vulnerability still widespread?
