Design mode-Memo mode

Source: Internet
Author: User

Intent: To get and save the state inside the object without destroying the encapsulation of the object, so that the object can revert back to its original state. Like the internal information of the Backup object.

Participants:

Memento (Memo), which stores the internal state of the original generator.

Originator, create a memo, record your current status, and use a memo to restore the state of an object.

Caretaker (person in charge), responsible for keeping the memo, and the protection memo cannot be changed.

Cons: The cost of using a memo is high, and it can be expensive to copy and store large amounts of data when the original is created, or to frequently create and restore the state of the original generator.

The Java code is implemented as follows:

Package Com.zqwei.memento;public class Originator {private Memento memento;private String name = null;public Originator (S Tring name) {this.name = name;} Public Memento Creatememento () {return new Memento (name);} public void Restorememento (Memento Memento) {this.name = Memento.getname ();} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} public class Memento {private string name;public Memento (String name) {this.name = name;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}} public class Caretaker {private Memento memento;public caretaker (Memento Memento) {this.memento = Memento;} Public Memento Getmemento () {return Memento;}} public class Test {public static void main (string[] args) {originator Ori = new Originator ("Zhangsan"); Caretaker caretaker = new Caretaker (Ori.creatememento ()); System.out.println ("before modify, name is" +ori.getname ()); Ori.setname ("Lisi"); System.out.println ("After Modify,name is" +ori.getName ()); Ori.restorememento (Caretaker.getmemento ()); SYSTEM.OUT.PRINTLN ("After restore, name is" +ori.getname ());}}

Design mode-Memo mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.