Hej, właśnie obniżyłem ceny wszystkich produktów. Przygotujmy nasze umiejętności programowania na erę post-COVID. Więcej szczegółów »
Pamiątka

Pamiątka w języku Go

Pamiątka to behawioralny wzorzec projektowy umożliwiający zapisywanie “migawek” stanu obiektu i późniejsze jego przywracanie.

Wzorzec Pamiątka nie wpływa na wewnętrzną strukturę obiektu z którym współpracuje, ani na dane przechowywane w migawkach.

Przykład koncepcyjny

Wzorzec Pamiątka pozwala zapisywać migawki stanu obiektu. Można dzięki temu przywrócić obiekt do któregoś z pierwotnych stanów, co przydaje się szczególnie w implementacji funkcjonalności cofnij-ponów.

originator.go: Źródło

package main

type originator struct {
	state string
}

func (e *originator) createMemento() *memento {
	return &memento{state: e.state}
}

func (e *originator) restoreMemento(m *memento) {
	e.state = m.getSavedState()
}

func (e *originator) setState(state string) {
	e.state = state
}

func (e *originator) getState() string {
	return e.state
}

memento.go: Pamiątka

package main

type memento struct {
	state string
}

func (m *memento) getSavedState() string {
	return m.state
}

caretaker.go: Zarządca

package main

type caretaker struct {
	mementoArray []*memento
}

func (c *caretaker) addMemento(m *memento) {
	c.mementoArray = append(c.mementoArray, m)
}

func (c *caretaker) getMemento(index int) *memento {
	return c.mementoArray[index]
}

main.go: Kod klienta

package main

import "fmt"

func main() {

	caretaker := &caretaker{
		mementoArray: make([]*memento, 0),
	}

	originator := &originator{
		state: "A",
	}

	fmt.Printf("Originator Current State: %s\n", originator.getState())
	caretaker.addMemento(originator.createMemento())

	originator.setState("B")
	fmt.Printf("Originator Current State: %s\n", originator.getState())
	caretaker.addMemento(originator.createMemento())

	originator.setState("C")
	fmt.Printf("Originator Current State: %s\n", originator.getState())
	caretaker.addMemento(originator.createMemento())

	originator.restoreMemento(caretaker.getMemento(1))
	fmt.Printf("Restored to State: %s\n", originator.getState())

	originator.restoreMemento(caretaker.getMemento(0))
	fmt.Printf("Restored to State: %s\n", originator.getState())

}

output.txt: Wynik działania

originator Current State: A
originator Current State: B
originator Current State: C
Restored to State: B
Restored to State: A
Na podstawie: Golang By Example

Pamiątka w innych językach

Wzorce projektowe: Pamiątka w języku Java Wzorce projektowe: Pamiątka w języku C# Wzorce projektowe: Pamiątka w języku C++ Wzorce projektowe: Pamiątka w języku PHP Wzorce projektowe: Pamiątka w języku Python Wzorce projektowe: Pamiątka w języku Ruby Wzorce projektowe: Pamiątka w języku Swift Wzorce projektowe: Pamiątka w języku TypeScript