Null object design pattern is to make use of the object, be it not declared or having no value to be as a value. This allows a system to operate even at the absent of values or using such phenomenon to set "do nothing" action. This is often deployed in Singleton creational pattern. The design diagram is as follows:
Here is an example in Go:
package main
import (
"fmt"
)
func Print(d interface{}) {
if d == nil {
return
}
fmt.Printf("the value is: %v\n", d)
}
func main() {
Print("Hello")
Print(5)
Print(nil)
}
// Output:
// the value is: Hello
// the value is: 5
Notice that when given nil
to the Print
function, the function does nothing. This allows us to tell the function to "do nothing" instead of allocating some forms of flags.