Use the simplest example to understand Memento Pattern and mementopattern.

Source: Internet
Author: User

Use the simplest example to understand Memento Pattern and mementopattern.

In short, the memorandum mode supports rollback. Suppose a Notepad supports the rollback operation. How can this problem be achieved?


First, a memorandum class is required.

    public class Memento
    {
        private string _msg;
        public Memento(string msg)
        {
            _msg = msg;
        }
        public string GetText()
        {
            return _msg;
        }
    }

Above,
○ The constructor is called every time Nodepad records information. The information recorded by Nodepad is finally assigned to the _ msg field through this constructor.
○ The GetText method is called when the Nodepad performs the rollback operation.

 

The next step is the Nodepad class.

    public class Notepad
    {
        private string _msg;
        public Memento SetMsg(string msg)
        {
            Memento m = new Memento(msg);
            _msg = msg;
            return m;
        }
         
        public string GetMsg()
        {
            return _msg;
        }
        public void Undo(Memento previousState)
        {
            if (previousState != null)
            {
                _msg = previousState.GetText();
            }
            else
            {
                _msg = "";
            }
           
        }
    }

 

○ Maintain a string-type field _ msg, representing the text displayed on Nodepad
○ Record information method SetMsg: not only must the record information be assigned to _ msg, but also the information be transmitted to the memorandum class.
○ GetMsg: Read _ msg
○ Rollback operation method Undo: Assign the last message of the memo to _ msg. If you roll back to the previous operation for the first time, it is equivalent to the condition in which the memorandum is null and must be considered as null.

 

The client needs to have a list of memos for the maintainer.

    class Program
    {
        static void Main(string[] args)
        {
            IList<Memento> undos = new List<Memento>();
            Notepad notepad = new Notepad();
            Memento undo;
            undo = notepad.SetMsg("Hello");
            undos.Add(undo);
            undo = notepad.SetMsg("World");
            undos.Add(undo);
Console. WriteLine ("go to Nodepad to view information ");
            Console.WriteLine(notepad.GetMsg());
Console. WriteLine ("1. Perform a rollback operation ");
            notepad.Undo(undos[0]);
Console. WriteLine ("view information after rollback ");
            Console.WriteLine(notepad.GetMsg());
Console. WriteLine ("2. Perform another rollback operation ");
            notepad.Undo(null);
Console. WriteLine ("view information after rollback ");
            Console.WriteLine(notepad.GetMsg());
            Console.ReadKey();
        }
    }

○ The first time you enter Notepad to view information, you will see the last entered World;
○ Roll back once. The second time you enter Notepad to view the information, you will see the first Hello input;
○ Roll back again. For the third time, enter Notepad to view the information. An empty string is displayed.


What design patterns are familiar to you? Write the implementation code of Singleton Mode

There are 23 design modes in total!

Reference the "software secrets-the point of design patterns" book:

According to the purpose, the design patterns can be divided into creation patterns, structural patterns, and behavior patterns.
The creation mode is used to process the object creation process, the structure mode is used to process the combination of classes or objects, and the behavior mode is used to describe how classes or objects interact and how responsibilities are assigned.

The creation mode is used to process the object creation process. It mainly includes the following five design modes:
Factory Method Pattern)
Abstract Factory Pattern)
Builder Pattern)
Prototype Pattern)
Singleton Pattern)

The structural mode is used to process the combination of classes or objects. It mainly includes the following seven design modes:
Adapter Pattern)
Bridge Pattern)
Composite Pattern)
Decorator Pattern)
Facade Pattern)
Flyweight Pattern)
Proxy Pattern)

The behavior pattern is used to describe how classes or objects interact and how responsibilities are assigned. It mainly includes the following 11 design patterns:
Chain of Responsibility Pattern)
Command Pattern)
Interpreter mode (Interpreter Pattern)
Iterator Pattern)
Mediator Pattern)
Memory memorandum mode (Memento Pattern)
Observer Pattern)
State Pattern)
Strategy Pattern)
Template Method Pattern)
Visitor Pattern)

Singleton mode Implementation 1:
Public class Singleton {
// Class shared Instance Object
Private static Singleton singleton = null;
// Private constructor
Private Singleton (){
System. out. println ("-- this is Singleton !!! ");
}
// Obtain the singleton Method
Public synchronized static Singleton getInstance (){
// Determine whether the shared object is null. If it is null, a new object is created.
If (singleton = null ){
Singleton = new Singleton ();
}
Return singleton;
}
}

Singleton mode implementation 2:
Public class Singleton {
// Class shared Instance Object Instantiation
Private s... the remaining full text>

What are the design patterns?

There are three types of design patterns: creation, structure, and behavior.
The creation types include:
I. Singleton, Singleton mode: ensure that a class has only one instance and provide a global access point to it.
2. Abstract Factory: provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
3. Factory Method: Define an interface used to create objects, and let the subclass decide which class to instantiate. Factory Method delays the instantiation of a class to the subclass.
4. Builder: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.
5. Prototype: Use a Prototype instance to specify the type of the object to be created, and copy the Prototype to create a new object.
Behavior types:
6. Iterator: provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.
7. Observer: Observer mode: defines one-to-many dependencies between objects. When the status of an object changes, all objects dependent on it will be automatically updated by notification.
8. Template Method: defines the skeleton of an algorithm in an operation, and delays some steps to the subclass, templateMethod allows the subclass to redefine a specific step without changing the structure of an algorithm.
9. Command: encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests and record request logs, and supports unrecoverable operations.
10. State: allows an object to change its behavior when its internal State changes. The object seems to have changed its class.
11. Strategy: Define a series of algorithms, encapsulate them one by one, and enable them to replace each other. This mode allows algorithms to be independent of customers who use them.
12. China of Responsibility, Responsibility chain mode: Enables multiple objects to process requests to avoid coupling between the request sender and receiver.
13. Mediator: uses an intermediary object to encapsulate object interaction of some columns.
14. Visitor, Visitor mode: indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on this element without changing the element classes.
15th, Interpreter, Interpreter mode: a language is defined to define a representation of its grammar and an Interpreter. This Interpreter uses this representation to explain sentences in the language.
16. Memento: capture the internal state of an object without interrupting the object, and save the state outside the object.
There are:
17. Composite: Composite combines objects into a tree structure to represent the relationship between parts of the whole. Composite makes the use of a single object and a Composite object consistent.
18. Facade, appearance mode: provides a consistent interface for a group of interfaces in the subsystem. fa? Ade provides a high-level interface, which makes the subsystem easier to use.
19. Proxy: provides a Proxy for other objects to control access to this object.
20. Adapter: the Adapter mode converts a class of interfaces into another interface that the customer wants. The Adapter mode makes those classes unable to work together due to interface incompatibility.
21. Decrator: the Decorator mode dynamically adds some additional responsibilities to an object. In terms of the added functions, the Decorator mode is more flexible than the subclass generation mode.
22. Bridge: link the abstract Part with its implementation... the remaining full text>

Related Article

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.