当前位置:网站首页>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
边栏推荐
- [question 24] logic closed loop (Beijing Institute of Technology / Beijing University of Technology / programming methods and practice / primary school)
- Common shortcut keys and setting methods of idea
- How to realize a good knowledge management system?
- [question 22] dungeons and Warriors (Beijing Institute of Technology / Beijing Institute of Technology / programming methods and practice / primary school)
- Leetcode 301. delete invalid parentheses
- 数组扩容、排序、嵌套语句应用
- 枚举和注解
- After sorting (bubble sorting), learn to continuously update other sorting methods
- How to use Fiddler for weak network testing
- 怎么还有人问 MySQL 是如何归档数据的呢?
猜你喜欢

B站崩了,如果我们是那晚负责修复的开发人员

@Detailed introduction of requestparam annotation

Inertial navigation principle (VII) -imu error classification (II) -allan variance analysis method +imu test + calibration introduction

2022 2nd cyber edge cup cyber security competition Web

IDEA常用快捷键及设置方法

ThreadLocal principle and source code analysis (click in step by step, don't recite, learn ideas)

JVM garbage collection garbage collector and common combination parameters

Reentranlock and source code analysis (learn ideas and click the source code step by step)

How to customize logging of.Net6.0

Small change project (two versions) with detailed ideas
随机推荐
Why use MQ message oriented middleware? These questions must be solved
Live video source code, uni app to achieve advertising scroll bar
day 1 - day 4
2021-11-05类变量和类方法的理解
V2.x synchronization is abnormal. There are a lot of posts that cannot be synchronized in the cloud, and the synchronization is blocked and slow
Pytoch distributed training
【StoneDB故障诊断】MDL锁等待
异常-Exception
Software testing interview question: how many strategies are there for system testing?
排序(冒泡排序)后面学习持续更新其它排序方法
[question 23] Sudoku game with rotation | DFS (Beijing Institute of Technology / Beijing Institute of Technology / programming methods and practice / primary school)
More than 100 lines should be split into functions
An article takes you into the world of pycharm - stop asking me about pycharm installation and environment configuration!!!
How can anyone ask how MySQL archives data?
Station B collapsed. What did the developer responsible for the repair do that night?
Are Transformers Effective for Time Series Forecasting?|填坑
2021-11-05 understanding of class variables and class methods
Deepfake 换脸真假难辨,马斯克分克已伪装成功
项目分析(从技术到项目、产品)
Import word document pictures blocking and non blocking IO operations
