Last active
August 13, 2020 02:50
-
-
Save nguyentienlong/925f8571f149ddc7b75cbb2c4882d891 to your computer and use it in GitHub Desktop.
Open close principle implemented in 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
// https://longka.info/blog/2020/08/13/solid-open-close-principle-implemented-in-golang/ | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
type Shape interface { | |
GetArea() float64 | |
} | |
type Square struct { | |
Width float64 | |
} | |
func (s Square) GetArea() float64 { | |
return s.Width*s.Width | |
} | |
type Circle struct { | |
Radius float64 | |
} | |
func (c Circle) GetArea() float64 { | |
return c.Radius * c.Radius * math.Pi | |
} | |
type Rectangle struct { | |
Length float64 | |
Width float64 | |
} | |
func (r Rectangle) GetArea() float64 { | |
return r.Width * r.Length | |
} | |
type ShapeManager struct { | |
shapes []Shape | |
} | |
func (smgr *ShapeManager) AddShape(shape Shape) { | |
smgr.shapes = append(smgr.shapes, shape) | |
} | |
func (smgr ShapeManager) GetTotalArea() float64 { | |
total := 0.0 | |
for _, shape := range smgr.shapes { | |
total += shape.GetArea() | |
} | |
return total | |
} | |
func NewShapeManager() ShapeManager { | |
smgr := ShapeManager{} | |
smgr.shapes = []Shape{} | |
return smgr | |
} | |
func main() { | |
square := Square{10.0} | |
circle := Circle{12.0} | |
shapeManager := NewShapeManager() | |
shapeManager.AddShape(square) | |
shapeManager.AddShape(circle) | |
fmt.Printf("shapeManager %+v\n", shapeManager) | |
fmt.Println("Square Area ", square.GetArea()) | |
fmt.Println("Circle Area ", circle.GetArea()) | |
fmt.Println("Shape Manager Total Area ", shapeManager.GetTotalArea()) | |
// add rectangle | |
rect := Rectangle{5.0, 6.0} | |
fmt.Println("Rectangle Area ", rect.GetArea()) | |
shapeManager.AddShape(rect) | |
fmt.Printf("shapeManager %+v\n", shapeManager) | |
fmt.Println("Shape Manager Total Area ", shapeManager.GetTotalArea()) | |
} | |
// https://longka.info/blog/2020/08/13/solid-open-close-principle-implemented-in-golang/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment