Skip to content

Instantly share code, notes, and snippets.

@jerryan999
Last active November 20, 2021 16:33
Show Gist options
  • Save jerryan999/52734c81496950818e737cd38f7f47a5 to your computer and use it in GitHub Desktop.
Save jerryan999/52734c81496950818e737cd38f7f47a5 to your computer and use it in GitHub Desktop.
medium-adapt-design-pattern-golang.go
// adapter design pattern application in go language
package main
import (
"fmt"
"strconv"
)
// LightBulb class to be adapted to the Lighting interface (Adaptee)
// IsOn is a boolean property
// Assume it is not allowed to add more methods for other interfaces
type LightBulb struct {
IsOn bool
}
func (lightBulb *LightBulb) GetIsOn() bool {
return lightBulb.IsOn
}
func (lightBulb *LightBulb) SetIsOn(isOn bool) {
lightBulb.IsOn = isOn
}
// string method to implement the Stringer interface
func (lightBulb *LightBulb) String() string {
return "LightBulb: " + strconv.FormatBool(lightBulb.IsOn)
}
// Lighting interface
type Lighting interface {
Light()
}
// Adapter class for the light switch
type LightSwitchAdapter struct {
lightBulb LightBulb // adaptee object
}
// Adapter implementation of the Lighting interface
func (lightSwitchAdapter *LightSwitchAdapter) Light() {
lightBulb := lightSwitchAdapter.lightBulb
if lightBulb.GetIsOn() {
fmt.Println("Light is on, do nothing")
} else {
lightBulb.SetIsOn(true)
fmt.Println("Light is off, turning it on")
}
}
func main() {
// client code
// create a Lighting interface object
var lightSwitch Lighting = &LightSwitchAdapter{
lightBulb: LightBulb{true},
}
// use light switch
lightSwitch.Light()
}
package main
import (
"fmt"
)
//IProces interface
type IProcess interface {
process()
}
//Adapter struct
type Adapter struct {
adaptee Adaptee
}
//Adapter class method process
func (adapter Adapter) process() {
fmt.Println("Adapter process")
adapter.adaptee.convert()
}
//Adaptee Struct
type Adaptee struct {
adapterType int
}
// Adaptee class method convert
func (adaptee Adaptee) convert() {
fmt.Println("Adaptee convert method")
}
// main
func main() {
var processor IProcess = Adapter{}
processor.process()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment