• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Diving Into Design Patterns via Hacktoberfest

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,549
Баллы
155
How Did I Find a Project


Firstly, finding a project under hacktoberfest topic can be overwhelming, but somehow i found this

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

repository. So i found the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

about the Memento pattern and made a

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

. I did get learning experiences that i was not expecting.

Memento Pattern


Basically Memento pattern is used to undo/redo the object's state. The main question that comes up: "Do I need to save and restore an object's state?" → Use Memento. I displayed the player's current state based on the slot. The main logic is shown below:

client->originator->memento and client can call the caretaker for getting the states. client can call the caretaker to get the states. In the end, if you want to avoid manually controlling the player's state and changing the code everywhere, it is better to use the Memento pattern to make our lives easier.

Code Explanation


Firstly we need to take look at the the game-originator file.


public save(): PlayerMemento {
const state: Player = {
name: this.name,
health: this.health,
level: this.level,
isDead: this.isDead
};
return new PlayerMemento(state);
}

public restore(memento: IMemento): void {
const state = memento.getState();
this.name = state.name;
this.health = state.health;
this.isDead = state.isDead;
this.level = state.level;
}




With this class, we can restore and save the object. On the other hand, I use the game-caretaker class to store the history of the memento objects. Look at the code below:


private saveSlots: Map<string, IMemento> = new Map();

public saveToSlot(slotName: string, memento: IMemento): void {
this.saveSlots.set(slotName, memento);
}




Using the slot name, I can save the state in the hash map (though it's not restricted to Map only).

Lastly, these are our interfaces which will be implemented later:


export interface Player{
health: number;
level: number;
isDead: boolean;
name: string;
}

export interface IMemento{
getState(): Player;
}




The PlayerMemento class implements the Player interface and provides getState.
When it comes to the client code, it is more readable thanks to the memento pattern. Here is a code snippet from the client code:


const player = new PlayerState(100, 1, false, 'Hero');
const saveManager = new SaveManager();
console.log(player.getInfo());
player.levelUp();
saveManager.saveToSlot('beforeBattle',player.save());
console.log(player.getInfo());
console.log('Continue playing and leveling up');
player.levelUp();
saveManager.saveToSlot('cityZone', player.save());




100 is health and 1 is level this repo has demonstrating purposes. Therefore i have made it simple.

Explanatory Diagram:



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Unexpected Gained Knowledge


While implementing memento pattern i needed to write the test cases and thanks to this i got exposure to jest.js syntax. Eventually I got another

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

merged. Lastly, I highly recommend everybody to read this

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

book.



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу