Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class differentObj{
- private String nickname;
- public differentObj(String nickname){
- this.nickname=nickname;
- }
- public void setNickname(String nickname){
- //should be complex operation in here, i just make it simple to understand.
- this.nickname=nickname;
- }
- public String getNickname(){
- return nickname;
- }
- }
- class Originator {
- private String _name;
- private String _phone;
- private differentObj obj;
- public Originator(String name, String phone) {
- _name = name;
- _phone = phone;
- this.obj = new differentObj(name);
- }
- // Some operations make state changed
- public void someOperation() {
- obj.setNickname("1234");
- _name = "noboby";
- _phone = "911-911";
- }
- // recover object's state
- public void setMemento(Memento m) {
- _name = m.getName();
- _phone = m.getPhone();
- //same object with different memeory address but point to same point
- obj = m.getObj();
- }
- public Memento createMemento() {
- //how? how to due with complex object memento pattern?
- //how to save this object up?
- return new Memento(_name, _phone,obj); //<==obj, just give the same memeory allocation to the memento, cannot back up the object.
- }
- public void showInfo() {
- System.out.println( "Nicknameobj: " + obj.getNickname() +
- "\nName: " + _name +
- "\nPhone: " + _phone + "\n");
- }
- }
- class Memento {
- private String _name;
- private String _phone;
- private differentObj obj;
- public Memento(String name, String phone,differentObj obj) {
- _name = name;
- _phone = phone;
- this.obj=obj;
- }
- public differentObj getObj() {
- return obj;
- }
- public void setObj(differentObj obj) {
- this.obj=obj;
- }
- public String getName() {
- return _name;
- }
- public String getPhone() {
- return _phone;
- }
- public void setName(String name) {
- _name = name;
- }
- public void setPhone(String phone) {
- _phone = phone;
- }
- }
- class Caretaker {
- private Memento _memento;
- public void setMemento(Memento memento) {
- _memento = memento;
- }
- public Memento getMemento() {
- return _memento;
- }
- }
- public class test222 {
- public static void main(String[] args) {
- Originator originator = new Originator("Justin", "888-8888");
- Caretaker caretaker = new Caretaker();
- // save object's memento
- caretaker.setMemento(originator.createMemento());
- originator.showInfo();
- // some operations make the object's state changed
- originator.someOperation();
- originator.showInfo();
- // use memento to recover object's state
- originator.setMemento(caretaker.getMemento());
- originator.showInfo();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement