-
-
Save azhuox/48d03a95c53ca164c47ac8a1eb8d710e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package encapsulationexample | |
// Counter defines the interface that a counter instance needs to implement. | |
type Counter interface{ | |
N() int | |
Increment() | |
Reset() | |
} | |
// SimpleCounter - a simple counter. | |
type simpleCounter struct { | |
counter int | |
} | |
func NewSimpleCounter() Counter { | |
return &simpleCounter{ | |
counter: 0, | |
} | |
} | |
func (c *simpleCounter) N() int { return c.counter } | |
func (c *simpleCounter) Increment() { c.counter++ } | |
func (c *simpleCounter) Reset() { c.counter = 0 } | |
// CounterDemo shows how to use the `Counter` interface. | |
func CounterDemo() { | |
var c Counter | |
c = NewSimpleCounter() | |
// This would cause a compiler error as the `Counter` interface does not have `counter` field. | |
c.counter = 5 | |
// It will print out "counter value: 0" if you comment the above statement. | |
fmt.Print("counter value: %d\n", c.N()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment