[JAVA] Memento Pattern

Prepare a class that duplicates the state of a specific class and call it Memento. When user creates a duplicate, it instantiates Memento and records it in a collection, and retrieves the instance as needed.

Design Pattarm MENU

Check with the following class structure

class Explanation
Origin.class Class to be replicated
Memento.class When duplicating Origin, duplicate Origin data in Memento and save Memento
MementoList.class Holds a collection (List, Map, etc.) and stores a Memento instance
user(Main.class) Check the operation
  • User Includes the meaning that other developers use this pattern

Origin.class


class Origin{
  int  No;

  void setNo(int No){
       this.No=No;
  }

  Memento createMemento(){
       return new Memento(No);
  }
}

Memento.class


class Memento{     
  int No;          //Have the same field as Origin

  Memento(int No){
      this.No=No;
  }

  int getNo(){
      return No;
  }
}

MementoList.class


class MementoList{
  Map  map = new HashMap();

  void put(int key,Memento mmt){
       map.put(key,mmt);
  }
  
  Memento getMemento(int key){
       return (Memento) map.get(key);
  }
}

user(Main.class)


public static void main(String[] args){
  Origin or = new Origin();
  MementoList list = new MementoList();

  or.setNo(1);
     list.put(1,or.createMemento());
  or.setNo(2);
     list.put(2,or.createMemento());

  Memento m1 = list.getMemento(1);
  System.out.println(m1.getNo());
}

Recommended Posts

Memento Pattern
Design pattern ~ Memento ~
Prototype pattern
Mediator pattern
Iterator pattern
Composite pattern
Observer Pattern
Builder pattern
Bridge Pattern
Command Pattern
Builder Pattern
Strategy pattern
Iterator Pattern
Visitor pattern
Adapter Pattern
Proxy Pattern
Strategy Pattern
Composite Pattern
Singleton Pattern
Singleton pattern
Prototype Pattern
Facade Pattern
Decorator pattern
Flyweight Pattern
Decorator Pattern
Mediator Pattern
Facade pattern
Visitor Pattern
Bridge pattern
abstract Factory Pattern
Design pattern ~ Builder ~
[Java] Strategy pattern
Design pattern ~ Visitor ~
Java design pattern
java callback pattern
Design pattern ~ Proxy ~
Design pattern ~ State ~
Factory Method Pattern
Design pattern ~ Strategy ~
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (2): Builder
Design pattern (1): AbstractFactory
[Java] Singleton pattern
Design pattern ~ Command ~
Abstract Factory pattern
Design pattern ~ Iterator ~
Design pattern ~ Facade ~
Design pattern ~ Bridge ~
Design pattern ~ Mediator ~
Template Method pattern
Design pattern ~ Decorator ~
Template Method Pattern
Design pattern ~ Interpreter ~
Factory Method pattern
Design pattern ~ Observer ~
Design pattern ~ Prototype ~
[Java] Adapter pattern
Design pattern ~ Adapter ~
Design pattern ~ Flyweight ~
Java pattern memo