zoukankan      html  css  js  c++  java
  • 设计模式——备忘录模式

          备忘录模式又叫做快照模式(Snapshot Pattern)或Token模式,是对象的行为模式。

      备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。备忘录模式的用意是在不破坏封装的条件下,将一个对象的状态捕捉(Capture)住,并外部化,存储起来,从而可以在将来合适的时候把这个对象还原到存储起来的状态。备忘录模式常常与命令模式和迭代子模式一同使用。

          简单的说备忘录模式就是在想让对象回到原来某个时间点的状态时,可以通过撤销(undo)来简单的实现。

          在备忘录模式中,源发器对象是要备忘的对象。备忘录对象用来备忘某个时间点的对象状态。负责人对象用来记录备忘的那个时间点。

          备忘录有;两个重要的目标:一个是存储系统关键对象的重要状态,二是维护关键对象的封装。

          看一个介绍:http://www.cnblogs.com/java-my-life/archive/2012/06/06/2534942.html

           看一个Demo:

    /**
     * 源发器对象
     * @author wxisme
     *
     */
    public class Emp {
    	private String name;
    	private int age;
    	
    	public Emp(String name, int age) {
    		this.age = age;
    		this.name = name;
    	}
    	//数据恢复
    	public void recovery(EmpMemento emt) {
    		this.age = emt.getAge();
    		this.name = emt.getName();
    	}
    	//备忘
    	public EmpMemento memento() {
    		return new EmpMemento(this);
    	}
    	
    	
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    	
    	
    
    }
    
    public class EmpMemento {
    	private String name;
    	private int age;
    	
    	public EmpMemento(Emp emp) {
    		this.age = emp.getAge();
    		this.name = emp.getName();
    	}
    	
    	
    	
    	
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    	
    	
    }
    
    public class Taker {
    	private EmpMemento empm;
    
    	public EmpMemento getEmpm() {
    		return empm;
    	}
    
    	public void setEmpm(EmpMemento empm) {
    		this.empm = empm;
    	}
    	
    	
    }
    

     PS:深度备忘,保证对象中的属性对象不会随着源发对象的改变而改变,参考原型模式中的深度拷贝。

  • 相关阅读:
    swoole 安装方法 使用即时聊天
    git的介绍以及简单应用
    curl的应用
    linux下监听和同步代码配置
    mac skim 修改背景色
    php 编译安装的一个 configure 配置
    mac mysql error You must reset your password using ALTER USER statement before executing this statement.
    yii2 控制器里 action 大小写组合造成的路由问题
    warning : json_decode(): option JSON_BIGINT_AS_STRING not implemented in xxx
    redis 自启动脚本
  • 原文地址:https://www.cnblogs.com/wxisme/p/4540682.html
Copyright © 2011-2022 走看看