Created
December 10, 2021 00:14
-
-
Save jay-babu/9ec716931428656ee2a167942a12531a to your computer and use it in GitHub Desktop.
DI With Interfaces Golang
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
func main() { | |
area := ProvideShape() | |
fmt.Println(area) | |
} |
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
func provideSquare() *Square { | |
sq := Square{4} | |
return &sq | |
} | |
var ShapeSet = wire.NewSet( | |
provideSquare, | |
wire.Bind(new(Geometry), new(*Square)), | |
) | |
func provideArea(g Geometry) float64 { | |
return g.Area() | |
} | |
func ProvideShape() float64 { | |
panic(wire.Build(ShapeSet, provideArea)) | |
} |
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
type Geometry interface { | |
Area() float64 | |
Perimeter() float64 | |
Width() float64 | |
Height() float64 | |
SetWidth(float64) Geometry | |
SetHeight(float64) Geometry | |
} | |
type Square struct { | |
side float64 | |
} | |
func (s *Square) Area() float64 { | |
return s.side * s.side | |
} | |
func (s *Square) Perimeter() float64 { | |
return s.side * 4 | |
} | |
func (s *Square) Width() float64 { | |
return s.side | |
} | |
func (s *Square) Height() float64 { | |
return s.side | |
} | |
func (s *Square) SetWidth(f float64) Geometry { | |
s.side = f | |
return s | |
} | |
func (s *Square) SetHeight(f float64) Geometry { | |
s.side = f | |
return s | |
} | |
type Rectangle struct { | |
width float64 | |
height float64 | |
} | |
func (s *Rectangle) Area() float64 { | |
return s.width * s.height | |
} | |
func (s *Rectangle) Perimeter() float64 { | |
return 2 * (s.width + s.height) | |
} | |
func (s *Rectangle) Width() float64 { | |
return s.width | |
} | |
func (s *Rectangle) Height() float64 { | |
return s.height | |
} | |
func (s *Rectangle) SetWidth(f float64) Geometry { | |
s.width = f | |
return s | |
} | |
func (s *Rectangle) SetHeight(f float64) Geometry { | |
s.height = f | |
return s | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment