设计模式 - 空对象模式
在空对象模式(Null Object Pattern)中,一个空对象取代 NULL 对象实例的检查。Null 对象不是检查空值,而是反应一个不做任何动作的关系。这样的 Null 对象也可以在数据不可用的时候提供默认的行为。
在空对象模式中,我们创建一个指定各种要执行的操作的抽象类和扩展该类的实体类,还创建一个未对该类做任何实现的空对象类,该空对象类将无缝地使用在需要检查空值的地方。
package main import "fmt" type AbstractCustomer interface { IsNil() bool GetName() string } type RealCustomer struct { Name string } func NewRealCustomer(name string) *RealCustomer { return &RealCustomer{ Name: name, } } func (r *RealCustomer) GetName() string { return r.Name } func (*RealCustomer) IsNil() bool { return false } type NullCustomer struct{} func (n *NullCustomer) GetName() string { return "Not available in customer db" } func (*NullCustomer) IsNil() bool { return true } type CustomerFactory struct { Names []string } func NewCustomerFacotry() *CustomerFactory { return &CustomerFactory{ Names: []string{"Rob", "Joe", "Julie"}, } } func (c *CustomerFactory) GetCustomer(name string) AbstractCustomer { for _, n := range c.Names { if n == name { return NewRealCustomer(name) } } return &NullCustomer{} } func main() { factory := NewCustomerFacotry() customer1 := factory.GetCustomer("Rob") customer2 := factory.GetCustomer("Bob") customer3 := factory.GetCustomer("Julie") customer4 := factory.GetCustomer("Laura") fmt.Println("customers: ") fmt.Println(customer1.GetName()) fmt.Println(customer2.GetName()) fmt.Println(customer3.GetName()) fmt.Println(customer4.GetName()) }
Jan 18, 2023 03:58:45 PM
The Null Object pattern is a design pattern that is used to represent the absence of a real object of a class. It is often used as a substitute for a null value or a null reference, and it can be used to avoid having to check for null values or references when working with objects. The Lab grown diamonds Null Object pattern typically defines a default or "null" implementation of an interface or abstract class, and it can be used to provide a consistent behavior when an object is not present or not known.