Design Model II 12: memo mode (Memento)

Everyone has to make mistakes, they both want a kind of "regret" to make up for their mistakes so that they start again, but the reality is cruel. In computer applications, customers will also often make mistakes, the availability of "regret" to them? Of course we can, but it is necessary. This function is implemented by "the memo mode."

In fact, many application software provides this functionality, such as Word, Notepad, Photoshop, Eclipse editing software such as when pressing Ctrl + Z key combination can be withdrawn when the current operation, the document back to the previous state; there is in IE the back key, rollback database transaction management, archiving intermediate results when playing games, operating system, database and backup operations, board games undo function belong to this category.

Memo mode can record the internal state of an object when the user regret can undo this operation, so that the data back to its original state.

The definition and characteristics of the model

Defined Memorandum (Memento) mode: without violating encapsulation, capture and the internal state of an object, and save the state of the object outside, so that later when an object needs to be able to restore the previously saved state. This mode is also called snapshot mode.

Memo mode is an object behavioral pattern, its main advantages are as follows.

  • It provides a mechanism to restore the state. When the user needs to be able to relatively easily recover data to the state of a history.
  • To achieve encapsulation of the internal states. In addition to creating its sponsors, other objects can not access the status information.
  • Simplifying the launch humans. Sponsors need to manage and preserve their internal state of each backup, all state information is stored in a memo by the managers manage, in line with the principle of single responsibility.


Its main drawback is: resource consumption. If you want to save too much internal state information or particularly frequent, it will take up a relatively large memory resources.

Architecture and Implementation Model

The core model is designed memo memorandum class and category manager for managing memo, and now we learn its structure and implementation.

1. Structure Model

The main role of the memo mode is as follows.

  1. Originator (Originator) Role: Record internal state information of current time, offer to create memos and memo data recovery, and achieve other business functions, it can access all the information in the memo.
  2. Memorandum (Memento) Role: responsible for storing the internal state sponsors, these internal states when needed to sponsor.
  3. Managers (Caretaker) role: to manage the memorandum, provide preservation and access the memo function, but it can not be accessed with a modification of the contents of the memo.


FIG memo mode configuration shown in Figure 1.
 

                        Memorandum mode structure of FIG.
 

2. Mode of realization

The memo mode codes are as follows:

 

package memento;
public class MementoPattern
{
    public static void main(String[] args)
    {
        Originator or=new Originator();
        Caretaker cr=new Caretaker();       
        or.setState("S0"); 
        System.out.println("初始状态:"+or.getState());           
        cr.setMemento(or.createMemento()); //保存状态      
        or.setState("S1"); 
        System.out.println("新的状态:"+or.getState());        
        or.restoreMemento(cr.getMemento()); //恢复状态
        System.out.println("恢复状态:"+or.getState());
    }
}
//备忘录
class Memento
{ 
    private String state; 
    public Memento(String state)
    { 
        this.state=state; 
    }     
    public void setState(String state)
    { 
        this.state=state; 
    }
    public String getState()
    { 
        return state; 
    }
}
//发起人
class Originator
{ 
    private String state;     
    public void setState(String state)
    { 
        this.state=state; 
    }
    public String getState()
    { 
        return state; 
    }
    public Memento createMemento()
    { 
        return new Memento(state); 
    } 
    public void restoreMemento(Memento m)
    { 
        this.setState(m.getState()); 
    } 
}
//管理者
class Caretaker
{ 
    private Memento memento;       
    public void setMemento(Memento m)
    { 
        memento=m; 
    }
    public Memento getMemento()
    { 
        return memento; 
    }
}

Results of the program run as follows: 

初始状态:S0
新的状态:S1
恢复状态:S0

Mode of application examples

Blind design game [Example 1] by using the memo mode.

Analysis: If there is beauty, Wang Zhaojun, Diao Chan, Yang Yuhuan Four Beauties with your blind date, you can choose one of them as your lover; of course, if you are not satisfied with the choice of front, you can re-select, but I hope you Do not bother too much; this game offers regret functionality, design more appropriate use, "the memo mode."

First, let's design a beautiful (Girl) class, which is the role of the memorandum, they provide the ability to store and beauty information; then design a blind date (You) class, which is the initiator role, it records the internal state of the current time information (temporary wife's name), and provides create memos and memo data recovery; and finally, the definition of a beautiful stack (GirlStack) class, which is the role of the manager is responsible for managing memo, save for blind persons (You) in front of the selectmen beauty information, but can only save four, offers regret function.

Client class is designed to form a program, comprising beauty stack (GirlStack) objects and blind persons (You) object that implements the event handling method ActionListener interface actionPerformed (ActionEvent e), and 4 large and beautiful images blind persons (You ) beauty selected image is displayed on the form. Figure 2 is a structural view.
 

                       Figure structure dating game


Code is as follows:

package memento;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class DatingGame
{
    public static void main(String[] args)
    {
        new DatingGameWin();
    }
}
//客户窗体类
class DatingGameWin extends JFrame implements ActionListener
{
    private static final long serialVersionUID=1L;   
    JPanel CenterJP,EastJP;
    JRadioButton girl1,girl2,girl3,girl4;
    JButton button1,button2;
    String FileName;
    JLabel g;
    You you;
    GirlStack girls;
    DatingGameWin()
    {
        super("利用备忘录模式设计相亲游戏");
        you=new You();
        girls=new GirlStack();       
        this.setBounds(0,0,900,380);            
        this.setResizable(false);
        FileName="src/memento/Photo/四大美女.jpg";   
        g=new JLabel(new ImageIcon(FileName),JLabel.CENTER);
        CenterJP=new JPanel();
        CenterJP.setLayout(new GridLayout(1,4));
        CenterJP.setBorder(BorderFactory.createTitledBorder("四大美女如下:"));
        CenterJP.add(g);   
        this.add("Center",CenterJP);
        EastJP=new JPanel();
        EastJP.setLayout(new GridLayout(1,1));
        EastJP.setBorder(BorderFactory.createTitledBorder("您选择的爱人是:"));
        this.add("East",EastJP);
        JPanel SouthJP=new JPanel();      
        JLabel info=new JLabel("四大美女有“沉鱼落雁之容、闭月羞花之貌”,您选择谁?");
        girl1=new JRadioButton("西施",true);
        girl2=new JRadioButton("貂蝉");
        girl3=new JRadioButton("王昭君");       
        girl4=new JRadioButton("杨玉环");
        button1=new JButton("确定");
        button2=new JButton("返回");
        ButtonGroup group=new ButtonGroup();
        group.add(girl1);
        group.add(girl2);
        group.add(girl3);
        group.add(girl4);
        SouthJP.add(info);
        SouthJP.add(girl1);
        SouthJP.add(girl2);
        SouthJP.add(girl3);
        SouthJP.add(girl4);
        SouthJP.add(button1);
        SouthJP.add(button2);
        button1.addActionListener(this);
        button2.addActionListener(this);
        this.add("South",SouthJP);        
        showPicture("空白");
        you.setWife("空白");
        girls.push(you.createMemento());    //保存状态
    }
    //显示图片
    void showPicture(String name)
    {
        EastJP.removeAll(); //清除面板内容
        EastJP.repaint(); //刷新屏幕
        you.setWife(name);        
        FileName="src/memento/Photo/"+name+".jpg";               
        g=new JLabel(new ImageIcon(FileName),JLabel.CENTER);                   
        EastJP.add(g);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            
    }
    @Override
    public void actionPerformed(ActionEvent e)
    {
        boolean ok=false;
        if(e.getSource()==button1)
        {
            ok=girls.push(you.createMemento());    //保存状态  
            if(ok && girl1.isSelected())
            {
                showPicture("西施");
            }
            else if(ok && girl2.isSelected())
            {
                showPicture("貂蝉");
            }
            else if(ok && girl3.isSelected())
            {
                showPicture("王昭君");
            }
            else if(ok && girl4.isSelected())
            {
                showPicture("杨玉环");
            }               
        }
        else if(e.getSource()==button2)
        {
            you.restoreMemento(girls.pop()); //恢复状态
            showPicture(you.getWife());
        }
    }
}
//备忘录:美女
class Girl
{ 
  private String name;
  public Girl(String name)
  { 
      this.name=name; 
  }     
  public void setName(String name)
  { 
      this.name=name; 
  }
  public String getName()
  { 
      return name; 
  }
}
//发起人:您
class You
{ 
    private String wifeName;    //妻子
    public void setWife(String name)
    { 
        wifeName=name; 
    }
    public String getWife()
    { 
        return wifeName; 
    }
    public Girl createMemento()
    { 
        return new Girl(wifeName); 
    }
    public void restoreMemento(Girl p)
    { 
        setWife(p.getName());
    } 
}
//管理者:美女栈
class GirlStack
{ 
    private Girl girl[];
    private int top;
    GirlStack()
    {
        girl=new Girl[5];
        top=-1;
    }
    public boolean push(Girl p)
    {
        if(top>=4)
        {
            System.out.println("你太花心了,变来变去的!");
            return false;
        }
        else
        {
            girl[++top]=p;
            return true;
        }
    }
    public Girl pop()
    {
        if(top<=0)
        {
            System.out.println("美女栈空了!");
            return girl[0];
        }
        else return girl[top--]; 
    }
}

Result of the program shown in Figure 3.
 

                        Blind date operating results of the game

Application of scene modes

And the learned previously defined feature, structure and implementation of the memo mode, the application scenario now to the following mode.

  1. We need to save and restore data scenarios, such as archiving intermediate results when playing games.
  2. May be desirable to provide a rollback operation scenario, such as Word, Notepad, Photoshop, Eclipse software while editing press Ctrl + Z key combination, as well as transaction database operations.

Extended mode

In the memo mode described earlier, there are examples of a single backup state, and there are many examples of the state of the backup. Here's how the memo mode with the prototype model mix. In the memo mode, by defining the "Memorandum" to back up the information "sponsor" of the prototype and clone mode () method with self backup feature, so if you have let the promoters implement the Cloneable interface to back up their function, then you can be deleted memo category, the structure shown in Figure 4.
 

                     FIG memo mode configuration with prototypes


Codes are as follows:

package memento;
public class PrototypeMemento
{
    public static void main(String[] args)
    {
        OriginatorPrototype or=new OriginatorPrototype();
        PrototypeCaretaker cr=new PrototypeCaretaker();       
        or.setState("S0"); 
        System.out.println("初始状态:"+or.getState());           
        cr.setMemento(or.createMemento()); //保存状态      
        or.setState("S1"); 
        System.out.println("新的状态:"+or.getState());        
        or.restoreMemento(cr.getMemento()); //恢复状态
        System.out.println("恢复状态:"+or.getState());
    }
}
//发起人原型
class OriginatorPrototype  implements Cloneable
{ 
    private String state;     
    public void setState(String state)
    { 
        this.state=state; 
    }
    public String getState()
    { 
        return state; 
    }
    public OriginatorPrototype createMemento()
    { 
        return this.clone(); 
    } 
    public void restoreMemento(OriginatorPrototype opt)
    { 
        this.setState(opt.getState()); 
    }
    public OriginatorPrototype clone()
    {
        try
        {
            return (OriginatorPrototype) super.clone();
        }
        catch(CloneNotSupportedException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
//原型管理者
class PrototypeCaretaker
{ 
    private OriginatorPrototype opt;       
    public void setMemento(OriginatorPrototype opt)
    { 
        this.opt=opt; 
    }
    public OriginatorPrototype getMemento()
    { 
        return opt; 
    }
}

 Operating results of the program are as follows:

初始状态:S0
新的状态:S1
恢复状态:S0

 

Published 136 original articles · won praise 6 · views 1534

Guess you like

Origin blog.csdn.net/weixin_42073629/article/details/104437906