diff --git a/README.md b/README.md index 7d9f5f7..85b9b84 100644 --- a/README.md +++ b/README.md @@ -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 | ✘ | diff --git a/structural/bridge.md b/structural/bridge.md new file mode 100644 index 0000000..5ed9e4d --- /dev/null +++ b/structural/bridge.md @@ -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 | | +|-------------| ----|------> |------------------| +| + 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)