7

设计模式--备忘录(Memento)模式

 2 years ago
source link: https://segmentfault.com/a/1190000040406651
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态

  • 备忘录(Memento)存储原发器(Originator)对象的内部状态,在需要时恢复原发器状态
  • Memento模式的核心是信息隐藏,即Originator需要向外界隐藏信息,保持其封装性,但同时又需要将状态保持到外界(Memento)

Go语言代码实现

memento.go

package Memento

type Memento struct {
   state int
}

func NewMemento(value int) *Memento{
   return &Memento{value}
}

type Number struct {
   value int
}

func NewNumber (value int) *Number{
   return &Number{value: value}
}

func (n * Number) Double(){
   n.value = 2 * n.value
}

func (n *Number) Half () {
   n.value /= 2
}

func (n *Number) Value() int {
   return n.value
}

func (n *Number) CreateMemento() *Memento{
   return NewMemento(n.value)
}

func (n *Number) SetMemento(memento *Memento){
   n.value = memento.state
}

memento_test.go

package Memento

import (
   "fmt"
   "testing"
)

func TestNumber_SetMemento(t *testing.T) {
   n := NewNumber(7)
   n.Double()
   n.Double()
   memento := n.CreateMemento() //记录当前时刻的值
   n.Half()
   n.SetMemento(memento) //拿出当时记录的值
   fmt.Println(n.value)
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK