码迷,mamicode.com
首页 > 编程语言 > 详细

Java 设计模式 之 备忘录模式

时间:2018-06-28 10:14:32      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:模式   toc   pack   nta   creat   vat   port   public   .sh   

http://www.verejava.com/?id=16999143457673

package com.memento.theory;

import java.util.Stack;

public class TestMemento
{
    public static void main(String[] args)
    {
        MementoContainer container=new MementoContainer();
        
        Originator orig=new Originator();
        orig.setState("工作总结");
        container.push(orig.createMemento());
        
        orig.setState("工作报告");
        container.push(orig.createMemento());
        
        orig.setState("工作报告新春快乐");
        
        orig.show();
        
        orig.setMemento(container.back());
        orig.show();
        
        orig.setMemento(container.back());
        orig.show();
        
        orig.setMemento(container.forward());
        orig.show();
        
        orig.setMemento(container.forward());
        orig.show();
        
        
    }
}





package com.memento.theory;

public class Originator
{
    private String state;

    public Originator()
    {
        super();
    }

    public String getState()
    {
        return state;
    }

    public void setState(String state)
    {
        this.state = state;
    }

    public Memento createMemento()
    {
        return new Memento(state);
    }

    public void setMemento(Memento memento)
    {
        this.state = memento.getState();
    }
    
    public void show()
    {
        System.out.println(state);
    }
    
    
}





package com.memento.theory;

public class Memento
{
    private String state;

    public Memento(String state)
    {
        super();
        this.state = state;
    }

    public String getState()
    {
        return state;
    }

    public void setState(String state)
    {
        this.state = state;
    }
    
    
}





package com.memento.theory;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class MementoContainer
{
    private Stack<Memento> mementos;
    private int index;
    
    public MementoContainer()
    {
        mementos=new Stack<Memento>();
    }
    
    public void push(Memento memento)
    {
        mementos.push(memento);
        index++;
    }
    
    public Memento forward()
    {
        Memento memento=(Memento)mementos.get(index);
        index++;
        return memento;
    }
    
    public Memento back()
    {
        index--;
        Memento memento=(Memento)mementos.get(index);
        
        return memento;
    }
}

http://www.verejava.com/?id=16999143457673

Java 设计模式 之 备忘录模式

标签:模式   toc   pack   nta   creat   vat   port   public   .sh   

原文地址:https://www.cnblogs.com/verejava/p/9237054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!