1
0
Fork 0
mirror of https://github.com/tmrts/go-patterns.git synced 2025-04-04 05:33:33 +03:00
This commit is contained in:
Alexander Pantyukhin 2017-09-01 13:52:18 +00:00 committed by GitHub
commit 70907ae8e5
2 changed files with 82 additions and 1 deletions

View file

@ -28,7 +28,7 @@ A curated collection of idiomatic design & application patterns for Go language.
| [Bridge](/structural/bridge.md) | Decouples an interface from its implementation so that the two can vary independently | ✘ |
| [Composite](/structural/composite.md) | Encapsulates and provides access to a number of different objects | ✘ |
| [Decorator](/structural/decorator.md) | Adds behavior to an object, statically or dynamically | ✔ |
| [Facade](/structural/facade.md) | Uses one type as an API to a number of others | |
| [Facade](/structural/facade.md) | Uses one type as an API to a number of others | |
| [Flyweight](/structural/flyweight.md) | Reuses existing instances of objects with similar/identical state to minimize resource usage | ✘ |
| [Proxy](/structural/proxy.md) | Provides a surrogate for an object to control it's actions | ✔ |

81
structural/facade.md Normal file
View file

@ -0,0 +1,81 @@
# Facade Pattern
Facade design pattern provides a unified interface to a set
of interfaces in a subsystem. Facade defines a higher-level
interface that makes the subsystem easier to use
## Implementation
```go
package facade
// Models
type Product struct {
name string
cost float64
discount float64
}
type User struct {
name string
discount float64
}
// Storages
type ProductStorage struct {
storageMap map[string]Product
}
func (storage ProductStorage) GetProductByName(name string) Product{
product, ok := storage.storageMap[name]
if (!ok){
panic("Product is absent")
}
return product
}
type UserStorage struct {
storageMap map[string]User
}
func (storage UserStorage) GetUserByName(name string) User{
user, ok := storage.storageMap[name]
if (!ok){
panic("User is absent")
}
return user
}
// Facade
type ProductFacade struct {
productStorage ProductStorage
userStorage UserStorage
}
func (productFacade ProductFacade) GetDiscountedCost(userName string, productName string) float64 {
product := productFacade.productStorage.GetProductByName(productName)
user := productFacade.userStorage.GetUserByName(userName)
return product.cost * (1 - product.discount) * (1 - user.discount)
}
```
## Usage
```go
user := User{name: "Alex", discount: 0.2}
product := Product{name: "Car", cost:10.50, discount: 0.1 }
userStorage := UserStorage{storageMap: make(map[string]User)}
userStorage.storageMap[user.name] = user
productStorage := ProductStorage{storageMap: make(map[string]Product)}
productStorage.storageMap[product.name] = product
facade := ProductFacade{productStorage: productStorage, userStorage: userStorage}
discount := facade.GetDiscountedCost("Alex", "Car")
fmt.Printf("Cost with discount is: %f", discount)
```