In Go we can create functions that implement an interface, like http.Handler
interface and concrete type http.HandlerFunc
. I created another simple example of this kind of pattern to calculate bonus for different employees.
type BonusCalculator interface {
Calculate(salary float64) float64
}
type BonusFunc func(salary float64) float64
func (bonus BonusFunc) Calculate(salary float64) float64 {
return bonus(salary)
}
var (
DeveloperBonus BonusFunc = func(salary float64) float64 { return salary*1.5 + 2500.00 }
ManagerBonus BonusFunc = func(salary float64) float64 { return salary * 2.0 }
DirectorBonus BonusFunc = func(salary float64) float64 { return salary * 3.3 }
)
func CalculateBonus (bonus BonusCalculator, salary float64) float64 {
return bonus.Calculate(salary)
}
func main() {
bonus := CalculateBonus(DirectorBonus, 35000.00)
fmt.Printf("bonus %.2f", bonus)
}
So above we have simple BonusFuncs
implementing interface BonusCalculator
instead of use structs to do the same.
Is there a name to this pattern? I see it in many places and never found a name for it.