Design Patterns Learning Notes-Memo (Memento) mode

Source: Internet
Author: User
Tags generator
Design Patterns Learning Notes-Memo (Memento) mode

@ (design mode) [design mode, Memo mode, Memento]

Design Patterns Learning Notes Memo Memento Mode Basic Introduction Memo case class diagram implementation code Memento Class gamer class test class Run Results Memo mode role originator Generator Memento souvenir caretaker responsible for human figure

Basic Introduction

The basic functionality provided by the memo mode is to save the object state information (snapshot), Undo, Redo, and history.
The memo mode typically provides two interfaces: a wide interface and a narrow interface. The full object state can be obtained through a wide interface, exposing the internal information of the memo object. Through the narrow interface, only limited access to the information, the developer limited, can effectively prevent information disclosure. Memo Case class Diagram

Implementation Code Memento class

Package com.pc.memento.example;

Import java.util.ArrayList;
Import java.util.List;

/**
 * Memo Class
 * Created by Switch on 2017/3/31.
 */Public
class Memento {
    /**
     * Held money */
    private int;
    /**
     * Obtained fruit *
     *
    private list<string> fruits;

    /**
     * Get the money currently held
     *
     * @return Hold Money *
    /public int Getmoney () {
        return;
    }

    /**
     * Construct method, initialize the amount of money held *
     * @param money initialization Money
     *
    /Memento (int money) {
        This.money = money;
        This.fruits = new arraylist<> ();
    }

    /**
     * Add Fruit
     *
     * @param fruit Fruit * *
    void addfruit (String fruit) {
        fruits.add (fruit);
    }

    /**
     * Add all currently held fruit
     *
     * @return Fruit list *
    /list<string> getfruits () {
        return Fruits;
    }
}
Gamer Class
Package com.pc.memento.example;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;

Import Java.util.Random;
 /** * Player class * Created by Switch on 2017/3/31.
    */public class Gamer {/** * held money */private int;
    /** * Obtained fruit */private list<string> fruits = new arraylist<> ();
    /** * Random number generator */private random random = new random ();

    /** * denotes an array of fruit types */private static string[] Fruitsname = {"Apple", "grape", "banana", "orange"};
    /** * Construct method, initialize the money number * * @param money Number */public Gamer (int money) {This.money =;
    }/** * Gets the current number of dollars * * @return money */public int Getmoney () {return money;
        }/** * Throw dice to play games */public void bet () {//Get dice value int dice = random.nextint (6) + 1;
            if (dice = = 1) {This.money + = 100; System.out.println ("The money held has increased.
        "); }else if (dice = = 2) {This.money/= 2; System.out.println ("Half of the money held.")
        ");
            } else if (dice = = 6) {String F = this.getfruit (); System.out.println ("Get the fruit (" + f + ").
            ");
        This.fruits.add (f); } else {System.out.println ("nothing happened.
        ");  }}/** * Create Memo * * @return Memo Object */Public Memento Creatememento () {Memento m =
        New Memento (money);
        Iterator<string> it = Fruits.iterator ();
            while (It.hasnext ()) {String fruit = it.next ();
            if (Fruit.startswith ("tasty")) {m.addfruit (fruit);
    }} return m;
        }/** * Undo to specified Memo * * @param Memento Memo Object */public void Restorememento (Memento memento) {
        This.money = Memento.getmoney ();
    This.fruits = Memento.getfruits (); /** * Get a fruit * * @return fruit * */private String GETFRuit () {String prefix = "";
        if (Random.nextboolean ()) {prefix = "tasty";
    } return prefix + fruitsname[random.nextint (fruitsname.length)];
    } @Override Public String toString () {return "gamer{money=" + Money + ", fruits=" + Fruits + '} '; }
}
Test Class
Package com.pc.memento.example.test;
Import Com.pc.memento.example.Gamer;
Import Com.pc.memento.example.Memento;

Import Org.junit.Test;
 /** * Memento Tester. * * @author Switch * @version 1.0 */public class Mementotest {/** * Test Memo Mode */@Test public voi
        D Testmemento () {Gamer Gamer = new Gamer (100);
        Memento Memento = Gamer.creatememento ();
            for (int i = 0; i <; i++) {System.out.println ("= = =" + i);
            System.out.println ("Current status:" + gamer);

            Throw Dice Gamer.bet (); System.out.println ("The money held is" + gamer.getmoney () + "Yuan.
            "); How to handle Memento if (Gamer.getmoney () > Memento.getmoney ()) {System.out.println ("the money held increases
                So that the current state of the game is saved) ");
            Memento = Gamer.creatememento (); } else if (Gamer.getmoney () < Memento.getmoney ()/2) {System.out.println ("(The money held is much reduced, so the game reverts to the previous
                (state) "); GamEr.restorememento (Memento);
            }//wait for a period of time try {thread.sleep (100);
        } catch (Interruptedexception e) {} System.out.println (""); }
    }
}
Run Results
= = 0 Current Status: gamer{money=100, fruits=[]} nothing happened.

The money held was $100.
= = 1 Current status: gamer{money=100, fruits=[]} Half of the money held.

The money held was $50.
= = 2 Current status: gamer{money=50, fruits=[]} Half of the money held.
    The money held was $25.
(The money held down a lot, so the game back to the previous state) = = 3 Current status: gamer{money=100, fruits=[]} obtained fruit (delicious grapes).

The money held was $100.
= = 4 Current status: gamer{money=100, fruits=[Delicious grapes]} The money held increased.
    The money held was $200.
(The money you hold increases a lot, so save the current state of the game) = = 5 Current status: gamer{money=200, fruits=[Delicious grapes]} has halved the money held.

The money held was $100.
= = 6 Current status: gamer{money=100, fruits=[Delicious grapes]} obtained fruit (grape).

The money held was $100.
= = 7 Current status: gamer{money=100, fruits=[delicious grapes, grapes]} The money held increased.

The money held was $200.
= = 8 Current status: gamer{money=200, fruits=[delicious grapes, grapes] the money held in half.

The money held was $100.
= = 9 Current status: gamer{money=100, fruits=[delicious grapes, grapes]} The money held increased.

The money held was $200.
= = 10 Current status: gamer{money=200, fruits=[delicious grapes, grapes]} nothing happened.

The money held was $200.
= = 11 Current Status: gamer{money=200, fruits=[delicious grapes, grapes]} The money held increased.
    The money held was $300.
(The money you hold increases a lot, so save the current state of the game) = = 12 Current status: gamer{money=300, fruits=[delicious grapes, grapes]} The money held increased.
    The money held was $400. (The money you hold increases a lot, so save the current state of the game) = = 13 Current status: gamer{money=400, fruits=[delicious grapes, grapes] the money held in half.

The money held was $200.
= = 14 Current status: gamer{money=200, fruits=[delicious grapes, grapes]} obtained fruit (grape).

The money held was $200.
= = 15 Current status: gamer{money=200, fruits=[delicious grapes, grapes, grapes]} obtained fruit (delicious oranges).

The money held was $200.
= = 16 Current status: gamer{money=200, fruits=[delicious grapes, grapes, grapes, delicious oranges]} nothing happened.

The money held was $200.
= = 17 Current status: gamer{money=200, fruits=[delicious grapes, grapes, grapes, delicious oranges] the money held increased.

The money held was $300.
= = 18 Current status: gamer{money=300, fruits=[delicious grapes, grapes, grapes, delicious oranges] The money held in half.
    The money held was $150.
(The money held is reduced a lot, so the game back to the previous state) = = 19 Current status: gamer{money=400, fruits=[Delicious grapes]} nothing happened. The money held was $400.
roles in memo mode originator (generated by)

The originator role generates the memento role when it saves its latest state. When a previously saved memento role is passed to the originator role, it reverts itself to the state when the memento role was generated. In the case, this role is played by the gamer class. Memento (Souvenir)

The memento role consolidates the internal information of the originator role. Although the information for the originator role is saved in the memento role, it does not expose the information externally.
The memento role has the following two types of interfaces (APIs). Wide interface--Wide Interface (API)
The "Wide Interface (API)" provided by the memento role refers to the collection of all methods used to obtain the state information of the recovered object. Because the wide interface (API) exposes internal information for all memento roles, only the originator role is able to use the wide interface (API). Narrow interface--Narrow Interface (API)
The memento role provides a "narrow interface (API)" for external caretaker roles. The internal information of the memento role, which can be obtained through narrow interfaces (APIs), is very limited, thus effectively preventing information disclosure.

By providing these two interfaces (APIs) externally, it is possible to effectively prevent the encapsulation of objects from being destroyed.
In the case, this role is played by the Memento class.
There is a very close relationship between the originator role and the memento role. Caretaker (person in charge)

The originator role is notified when the caretaker role wants to save the state of the current originator role. The originator role generates an instance of the memento role and returns it to the caretaker role after receiving the notification. Because the memento instance may be used later to restore originator to its original state, the caretaker role will always save the memento instance. In the case, this role is played by the Test class.
However, the caretaker role can only use the narrow interface (API) in the Memento Role interface (API), which means that it cannot access all information inside the memento role. It simply saves the memento character generated by the originator role as a black box.
Although there is a strong association between the originator role and the memento role, there is a weak association between the caretaker role and the memento role. The memento role hides its own internal information from the caretaker role. class Diagram

Github:designpatternstudy

—————— Reference "Graphic design 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.