From 50062f15c2dcb316f4daabd9f1e450491c2bfa09 Mon Sep 17 00:00:00 2001 From: 18695049 Date: Mon, 17 May 2021 15:32:47 +0300 Subject: [PATCH] structural/decorator: adding exmample for interface --- structural/decorator.md | 66 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/structural/decorator.md b/structural/decorator.md index cfb769f..84077ea 100644 --- a/structural/decorator.md +++ b/structural/decorator.md @@ -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. @@ -23,7 +24,7 @@ func LogDecorate(fn Object) Object { } ``` -## Usage +### Usage ```go func Double(n int) int { return n * 2 @@ -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. + +