24.Golang设计模式之空对象模式

空对象模式

GitHub代码链接

什么是空对象模式

空对象模式(Null Object Pattern),使用空对象来取代Null对象实例的检测。

解决了什么问题

Null对象不是空值,而是返回一个不做任何动作的空对象。这样Null对象也可以在数据
不可用的时候执行一些默认动作。

代码实现

1. 抽象接口实现

//AbstractCustomer 客户对象接口
type AbstractCustomer interface {
    Isnil() bool
    GetName() string
}

2. 实例对象类实现

//RealCustomer 真实客户对象类
type RealCustomer struct {
    Name string
}

//NewRealCustomer 实例化真实客户对象
func NewRealCustomer(name string) *RealCustomer {
    return &RealCustomer{
        Name: name,
    }
}

//Isnil 真实客户对象nil判断
func (r *RealCustomer) Isnil() bool {
    return false
}

//GetName 获取真实客户对象名称
func (r *RealCustomer) GetName() (name string) {
    return r.Name
}

3. 空对象类实现

//NullCustomer 空客户对象类
type NullCustomer struct {
    Name string
}

//NewNullCustomer 实例化空客户对象
func NewNullCustomer() *NullCustomer {
    return &NullCustomer{}
}

//Isnil 空客户对象nil判断
func (n *NullCustomer) Isnil() bool {
    return true
}

//GetName 空客户对象获取名称
func (n *NullCustomer) GetName() (name string) {
    return "Not Available in Customer Database"
}

4. 客户工厂类

客户工厂类用于获取客户,如果客户名称不在工厂类中,就返回空对象。

//CustomerFactory 客户工厂类
type CustomerFactory struct {
    Names []string
}

//NewCustomerFactory 实例化客户工厂类
func NewCustomerFactory() *CustomerFactory {
    return &CustomerFactory{
        Names: []string{"Bob", "Lily", "James"},
    }
}

//GetCustomer 从客户工厂类获取客户对象
func (c *CustomerFactory) GetCustomer(name string) AbstractCustomer {
    for _, v := range c.Names {
        if v == name {
            return NewRealCustomer(name)
        }
    }
    return NewNullCustomer()
}

5. 测试

func NullObjectPatternTest(t *testing.T) {
    customerFactory := NewCustomerFactory()

    customer1 := customerFactory.GetCustomer("Lily")
    customer2 := customerFactory.GetCustomer("Allen")
    customer3 := customerFactory.GetCustomer("James")
    customer4 := customerFactory.GetCustomer("Bob")
    customer5 := customerFactory.GetCustomer("Jay")

    fmt.Println(customer1.GetName())
    fmt.Println(customer2.GetName())
    fmt.Println(customer3.GetName())
    fmt.Println(customer4.GetName())
    fmt.Println(customer5.GetName())
}

上一篇

23.Golang设计模式之状态模式

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。