The schema definition

Separate the abstract part (the business function) from the implementation part (the platform implementation) so that both can change independently.

The class diagram

Application scenarios

The bridging pattern is used when the business function has abstract functionality and different implementations that require independent adaptation to changes that may be encountered later

advantages

1. Comply with the Open Closed Principle

2. Provide methods but hide the underlying implementation

3. Separating functionality from implementation facilitates decoupling

The point to summarize

  • The Bridge pattern uses “combinational relationships between objects” to decouple the inherent binding between abstraction and implementation, allowing them to vary along their respective dimensions, or “subclass” them
  • Bridge is sometimes similar to multiple inheritance schemes, but multiple inheritance schemes often violate the principle of single responsibility and have poor reusability. Bridge is a better solution than multiple inheritance schemes.
  • The Bridge pattern is generally applied in “two very strong dimensions of variation”, and sometimes a class has more than two dimensions of variation, where the Bridge extension pattern can be used.

Go language code implementation

Project directory

Bridge.go

package Bridge type Set struct { impl map[string]bool } func NewSet() *Set { return &Set{make(map[string]bool)} } func (s *Set) Add(key string) { s.impl[key] = true } func (s *Set) Iter(f func(key string)) { for key := range s.impl{ f(key) }}

Bridge_test.go

 package Bridge
 
 import (
    "fmt"
    "testing"
 )
 
 func TestNewSet(t *testing.T) {
    s := NewSet()
    s.Add("hello")
    s.Add("world")
    s.Iter(func(key string) {
       fmt.Printf("key: %s\n", key)
    })
 }