mirror of
https://github.com/tmrts/go-patterns.git
synced 2024-11-22 13:06:09 +03:00
add fleunt interface
This commit is contained in:
parent
f978e42036
commit
dd6d146ec4
@ -102,6 +102,7 @@ A curated collection of idiomatic design & application patterns for Go language.
|
||||
| Pattern | Description | Status |
|
||||
|:-------:|:----------- |:------:|
|
||||
| [Functional Options](/idiom/functional-options.md) | Allows creating clean APIs with sane defaults and idiomatic overrides | ✔ |
|
||||
| [Fluent interface](/idiom/fluent-interace.md) | Method for constructing object oriented APIs focused on better readability | ✔ |
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
|
77
idiom/fluent-interface.md
Normal file
77
idiom/fluent-interface.md
Normal file
@ -0,0 +1,77 @@
|
||||
# Fluent interface
|
||||
|
||||
Fluent interface is a method for constructing object oriented APIs
|
||||
focused on better readability. Implemented by using method chaining
|
||||
|
||||
## Implementation
|
||||
|
||||
```go
|
||||
package fluent
|
||||
|
||||
type Align int
|
||||
|
||||
const (
|
||||
Left = iota
|
||||
Center = iota
|
||||
Right = iota
|
||||
)
|
||||
|
||||
type TextContainer struct {
|
||||
Font string
|
||||
FontSize int
|
||||
Color string
|
||||
Align Align
|
||||
}
|
||||
|
||||
func NewTextContainer() *TextContainer {
|
||||
return &TextContainer{
|
||||
Font: "Helvetica",
|
||||
FontSize: 10,
|
||||
Color: "Red",
|
||||
Align: Left}
|
||||
}
|
||||
|
||||
func (tc *TextContainer) SetFont (font string) *TextContainer {
|
||||
tc.Font = font
|
||||
return tc
|
||||
}
|
||||
|
||||
func (tc *TextContainer) SetFontSize (fontSize int) *TextContainer {
|
||||
tc.FontSize = fontSize
|
||||
return tc
|
||||
}
|
||||
|
||||
func (tc *TextContainer) SetColor (color string) *TextContainer {
|
||||
tc.Color = color
|
||||
return tc
|
||||
}
|
||||
|
||||
func (tc *TextContainer) SetAlign (align Align) *TextContainer {
|
||||
tc.Align = align
|
||||
return tc
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
```go
|
||||
func getAlignText(align Align) string{
|
||||
switch align{
|
||||
case Left:
|
||||
return "Left"
|
||||
case Center:
|
||||
return "Center"
|
||||
case Right:
|
||||
return "Right"
|
||||
default:
|
||||
panic("Not determinated align")
|
||||
}
|
||||
}
|
||||
|
||||
tContainer := NewTextContainer()
|
||||
tContainer.SetFont("Calibri").SetFontSize(20).SetColor("Green").SetAlign(Center)
|
||||
|
||||
fmt.Printf("Font: %s\n", tContainer.Font)
|
||||
fmt.Printf("Font size: %v\n", tContainer.FontSize)
|
||||
fmt.Printf("Color: %s\n", tContainer.Color)
|
||||
fmt.Printf("Align: %s\n", getAlignText(tContainer.Align))
|
||||
```
|
Loading…
Reference in New Issue
Block a user