标签:number skin expect ber img info 设计 str ror
memento.go
package memento import ( "fmt" ) type State struct { Description string } type memento struct { state State } type originator struct { state State } func (o *originator) NewMemento() memento { return memento{state: o.state} } func (o *originator) ExtractAndStoreState(m memento) { //Does nothing o.state = m.state } type careTaker struct { mementoList []memento } func (c *careTaker) Add(m memento) { //Does nothing c.mementoList = append(c.mementoList, m) } func (c *careTaker) Memento(i int) (memento, error) { if len(c.mementoList) < i || i < 0 { return memento{}, fmt.Errorf("Index not found\n") } return c.mementoList[i], nil }
memento_test.go
package memento import ( "testing" ) func TestCareTaker_add(t *testing.T) { originator := originator{} originator.state = State{Description: "Idle"} careTaker := careTaker{} mem := originator.NewMemento() if mem.state.Description != "Idle" { t.Error("Expected state was not found") } currentLen := len(careTaker.mementoList) careTaker.Add(mem) if len(careTaker.mementoList) != currentLen+1 { t.Error("No new elements were added on the list") } } func TestCareTaker_Memento(t *testing.T) { originator := originator{} careTaker := careTaker{} originator.state = State{"Idle"} careTaker.Add(originator.NewMemento()) mem, err := careTaker.Memento(0) if err != nil { t.Fatal(err) } if mem.state.Description != "Idle" { t.Error("Unexpected state") } mem, err = careTaker.Memento(-1) if err == nil { t.Fatal("An error is expected when asking for a negative number but no error was found") } } func TestOriginator_ExtractAndStoreState(t *testing.T) { originator := originator{state: State{"Idle"}} idleMemento := originator.NewMemento() originator.ExtractAndStoreState(idleMemento) if originator.state.Description != "Idle" { t.Error("Unexpected state found") } }
标签:number skin expect ber img info 设计 str ror
原文地址:https://www.cnblogs.com/aguncn/p/11916874.html