1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-22 04:56:09 +03:00

structural/bridge: add bridge pattern

This commit is contained in:
Daniel Naveda 2018-10-21 13:17:45 +02:00
parent f978e42036
commit ae6583af79
2 changed files with 51 additions and 1 deletions

View File

@ -25,7 +25,7 @@ A curated collection of idiomatic design & application patterns for Go language.
| Pattern | Description | Status |
|:-------:|:----------- |:------:|
| [Bridge](/structural/bridge.md) | Decouples an interface from its implementation so that the two can vary independently | |
| [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 | ✘ |

50
structural/bridge.md Normal file
View File

@ -0,0 +1,50 @@
# Bridge Pattern
The [bridge pattern](https://en.wikipedia.org/wiki/Bridge_pattern) allows you to "decouple an abstraction from its implementation so that the two can vary independently". It does so by creating two hierarchies: Abstraction and Implementation.
```
Abstraction | Implementation
Hierarchy | Hierarchy
|
------------- | ------------------
| Abstraction | | imp | <Implementor> |
|-------------| ----|------> |------------------|
| + imp | | | implementation() |
------------- | ------------------
| ^
| |
| ---------------------
| | ConcreteImplementor |
| |---------------------|
| | implementation() |
| ---------------------
```
Note: In the literature, the `Abstraction` class is commonly represented as an "Abstract Class", meaning, children should be defined to instantiate it. Since Go does not explicitly support inheritance (and it has good reasons), that part was simplified by a concrete class modeled as a Struct.
## Implementation
```go
// Abstraction represents the concretion of the abstraction hierarchy of the bridge
type Abstraction struct {
imp Implementor
}
// Implementor represents the abstraction of the implementation hierarchy of the bridge
type Implementor interface {
implementation()
}
// ConcreteImplementor implements Implementor
type ConcreteImplementor struct{}
func (c *ConcreteImplementor) implementation() {
fmt.Println(`Some implementation here...`)
}
```
## Usage
```go
myObj := Abstraction{&ConcreteImplementor{}}
myObj.imp.implementation()
```
[view in the Playground](https://play.golang.org/p/qlFOfjYX5YQ)