Last active
March 29, 2023 05:32
-
-
Save achjailani/effda8a276d13006d4e74441a693fc02 to your computer and use it in GitHub Desktop.
Strategy Pattern in Go
This file contains hidden or 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 main | |
import ( | |
"fmt" | |
) | |
// Strategy is a strategy interface which should be implemented by | |
// the concrete strategies | |
type Strategy interface { | |
execute(p *Route) | |
} | |
// Route is an object for context (in strategy pattern) | |
type Route struct { | |
algo Strategy | |
} | |
// NewRoute is a constructor for Route | |
func NewRoute(s Strategy) *Route { | |
return &Route{ | |
algo: s, | |
} | |
} | |
// Set is a method to set strategy | |
func (r *Route) Set(s Strategy) { | |
r.algo = s | |
} | |
// Execute is a method to run main strategy method | |
func (r *Route) Execute() { | |
r.algo.execute(r) | |
} | |
// Road is a concrete strategy that should implement execute method | |
type Road struct{} | |
// execute is a method implementation | |
func (r *Road) execute(_ *Route) { | |
fmt.Println("Executed by Road") | |
} | |
// PublicTransport is a concrete strategy that should implement execute method | |
type PublicTransport struct{} | |
// execute is a method implementation | |
func (r *PublicTransport) execute(_ *Route) { | |
fmt.Println("Executed by PublicTransport") | |
} | |
// Walking is a concrete strategy that should implement execute method | |
type Walking struct{} | |
// execute is a method implementation | |
func (r *Walking) execute(_ *Route) { | |
fmt.Println("Executed by Walking") | |
} | |
func main() { | |
road := &Road{} | |
route := NewRoute(road) | |
route.Execute() | |
publicTransport := &PublicTransport{} | |
route.Set(publicTransport) | |
route.Execute() | |
walking := &Walking{} | |
route.Set(walking) | |
route.Execute() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment