package main import ( "fmt" "gitty.informatik.hs-mannheim.de/steger/pr3-code/go/04-design-pattern/patterns" ) type Counter struct { patterns.Subject Count int } func NewCounter() Counter { return Counter{patterns.NewSubject(), 0} } func (c *Counter) Inc() { c.Count++ c.Notify() } func (c *Counter) Dec() { c.Count-- c.Notify() } type CountPrinter struct { counter *Counter } func (cp *CountPrinter) Update() { fmt.Println("count updated to ", cp.counter.Count) } type CounterHistory struct { counter *Counter history []int } func (ch *CounterHistory) Update() { ch.history = append(ch.history, ch.counter.Count) } func main() { counter := NewCounter() history := CounterHistory{&counter, []int{}} counter.Register(&history) printer := CountPrinter{&counter} counter.Register(&printer) printerRegistered := true var input string for { fmt.Print("Enter a command (+: increment, -: decrement, q: quit): ") fmt.Scanln(&input) if len(input) != 1 { fmt.Println("Please enter a single character.") continue } switch input[0] { case '+': counter.Inc() case '-': counter.Dec() case 'p': if printerRegistered { counter.Unregister(&printer) } else { counter.Register(&printer) } printerRegistered = !printerRegistered case 'q': fmt.Println("Exiting...") fmt.Println(history.history) return default: fmt.Println("Unknown command. Use '+', '-', or 'q'.") } } }