Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | ✘ |
Expand Down
50 changes: 50 additions & 0 deletions structural/bridge.md
Original file line number Diff line number Diff line change
@@ -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)