Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

structural/decorator: adding example for interface #109

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion structural/decorator.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Decorator structural pattern allows extending the function of an existing object
Decorators provide a flexible method to extend functionality of objects.

## Implementation
### Decorating single function
`LogDecorate` decorates a function with the signature `func(int) int` that
manipulates integers and adds input/output logging capabilities.

Expand All @@ -23,7 +24,7 @@ func LogDecorate(fn Object) Object {
}
```

## Usage
### Usage
```go
func Double(n int) int {
return n * 2
Expand All @@ -36,6 +37,69 @@ f(5)
// Execution is completed with the result 10
```

### Decorating interface
To ease decoration of interface with multiple methods, you can declare base decorator. The base decorator should simply calls all methods, then you can just override only one method in your target decorator.


```go
type PasswordService interface {
CheckPassword(p string) bool
ChangePassword(p string)
// ... more methods
}

type BaseDecoratorPasswordService struct {
delegate PasswordService
}

func (r BaseDecoratorPasswordService) CheckPassword(a string) bool {
return r.delegate.CheckPassword(a)
}

func (r BaseDecoratorPasswordService) ChangePassword(b string) {
r.delegate.ChangePassword(b)
}

```

### Usage
```go
type Implementation struct {
}

func (r Implementation) CheckPassword(p string) bool {
// .. validating password
return true
}

func (r Implementation) ChangePassword(p string) {
fmt.Printf("Implementation::ChangePassword(%v)\n", p)
}


func NewBigInterfaceMethodBLogger(delegate PasswordService) PasswordService {
return &ChangePasswordLogger{BaseDecoratorPasswordService{delegate}}
}

type ChangePasswordLogger struct {
BaseDecoratorPasswordService
}

func (r ChangePasswordLogger) ChangePassword(b string) {
r.BaseDecoratorPasswordService.ChangePassword(b)
fmt.Println("ChangePassword() was called")
}

func main() {
ci := NewBigInterfaceMethodBLogger(&Implementation{})
ci.CheckPassword("echo123")
ci.ChangePassword("qwerty")
}
```


## Rules of Thumb
- Unlike Adapter pattern, the object to be decorated is obtained by **injection**.
- Decorators should not alter the interface of an object.