Golang Bridge Pattern

In this post, we will show how to implement the Bridge pattern in Golang with an example.

Bridge decouples the implementation from the abstraction. The abstract base class can be subclassed to provide different implementations and allow implementation details to be modified easily. 

The interface, which is a bridge, helps in making the functionality of concrete classes independent from the interface implementer classes. The bridge patterns allow the implementation details to change at runtime.

Golang Bridge Pattern Implementation

Let's say IDrawShape is an interface with the drawShape() method. DrawShape implements the IDrawShape interface. We create an IContour bridge interface with the drawContour() method. The Contour class implements the IContour interface. 

The following code demonstrates the bridge implementation.

Let's create a file named "bridge.go" and add the following source code to it:

package main

// importing fmt package
import (
	"fmt"
)

//IDrawShape interface
type IDrawShape interface {
	drawShape(x [5]float32, y [5]float32)
}

//DrawShape struct
type DrawShape struct{}

// DrawShape struct has  method draw Shape with float x and y coordinates
func (drawShape DrawShape) drawShape(x [5]float32, y [5]float32) {
	fmt.Println("Drawing Shape")
}

//IContour interace
type IContour interface {
	drawContour(x [5]float32, y [5]float32)
	resizeByFactor(factor int)
}

//DrawContour struct
type DrawContour struct {
	x      [5]float32
	y      [5]float32
	shape  DrawShape
	factor int
}

//DrawContour method drawContour given the coordinates
func (contour DrawContour) drawContour(x [5]float32, y [5]float32) {
	fmt.Println("Drawing Contour")
	contour.shape.drawShape(contour.x, contour.y)
}

//DrawContour method resizeByFactor given factor
func (contour DrawContour) resizeByFactor(factor int) {
	contour.factor = factor
}

// main method
func main() {

	var x = [5]float32{1, 2, 3, 4, 5}
	var y = [5]float32{1, 2, 3, 4, 5}
	var contour IContour = DrawContour{x, y, DrawShape{}, 2}

	contour.drawContour(x, y)
	contour.resizeByFactor(2)
}

Output:

G:\GoLang\examples>go run bridge.go
Drawing Contour
Drawing Shape

Comments