备忘录模式

canca17年前 (2007-03-26)设计模式281

//备忘录模式
//CopyRight(C) CAnca software Office.2006
//Created by CAnca.

public class MementoMode{
 public static void main(String[] args){
  studentInfo student = new studentInfo();
  student.setName("CAnca");
  student.setNumber(11);
  student.setScore(80.9F);
  
  //Enter
  crlf();
  
  //Store internal state
  ProspectMemory pm = new ProspectMemory();
  pm.setMemento(student.saveMemento());
  
  //Continue changing originator
  student.setName("Jacky");
  student.setNumber(32);
  student.setScore(60.5F);
  
  crlf();
  
  //Restore saved state
  student.RestoreMemento(pm.getMemento());
  
 }
 
 private static void crlf(){
  System.out.println();
 }
}
 
// "Originator"
class studentInfo{
 private String name;
 private int number;
 private float score;
 
 public String getName(){
  return this.name;
 }
 public void setName(String name){
  this.name = name;
  System.out.println("name:" + name);
 }
 
 public int getNumber(){
  return this.number;
 }
 public void setNumber(int number){
  this.number = number;
  System.out.println("number:" + number);
 }
 
 public float getScore(){
  return this.score;
 }
 public void setScore(float score){
  this.score = score;
  System.out.println("score:" + score);
 }
 
 public Memento saveMemento(){
  return new Memento(name,number,score);  
 }
 public void RestoreMemento(Memento m){
  this.setName(m.getName());
  this.setNumber(m.getNumber());
  this.setScore(m.getScore());
 }
}

//"Memento"
class Memento{
 private String name;
 private int number;
 private float score;
 
 //Constructor
 public Memento(String name,int number,float score){
  this.name = name;
  this.number = number;
  this.score = score;
 }
 
 public String getName(){
  return this.name;
 }
 public void setName(String name){
  this.name = name;
 }
 
 public int getNumber(){
  return this.number;
 }
 public void setNumber(int number){
  this.number = number;
 }
 
 public float getScore(){
  return this.score;
 }
 public void setScore(float score){
  this.score = score;
 }
}

// "Caretaker" 
class ProspectMemory{
 private Memento memento;
 
 public void setMemento(Memento memento){
  this.memento = memento;
 }
 public Memento getMemento(){
  return this.memento;
 }
}

 

相关文章

抽象工厂模式

//抽象工厂模式//Copyright CAnca Software office//Created by CAnca.2006public class AbstractFactory{ p...

单例模式

//CopyRight CAnca Software Office. 2006//Created by CAnca. import java.util.*; public class singleto...

工厂方法模式

//工厂方法模式:现实例子//CopyRight(C)CAnca Software Office. 2006//Created by CAnca. import java.util.*; public...

建造者模式

//建造者模式//CopyRight(C)CAnca Software Office.//Created by CAnca. import java.util.*; public class Buil...

原型模式

//原型模式//CopyRight(C) CAnca Software Office.2006//Created by CAnca. public class PrototypeMode{ ...

代理模式

//代理模式--真实例子//CopyRight(C)CAnca Software Office.2006//Created by CAnca.   public class ProxyMod...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。