前言
设计模式时一套被反复使用,多数人知晓的,经过分类编目的,代码设计经验总结的。使用设计模式是为了可重用代码、让他人更容易理解、保证代码的可靠性。
创建型模式
简单工厂模式
在go中没有构造函数这一说,所以一般会定义NewXXX函数来初始化相关的类型。NewXXX函数返回接口时就是简单工厂模式。
simlpefactory.go
package DesignPatterns
import "fmt"
//简单工厂模式
type Animal interface {
Eat()
Call()
}
func NewAnimal(animal string) Animal {
if animal == "cat" {
return Cat{}
} else if animal == "dog" {
return Dog{}
}
return nil
}
//猫
type Cat struct {
}
func (c Cat) Eat() {
fmt.Println("猫在吃")
}
func (c Cat) Call() {
fmt.Println("猫再叫")
}
//狗
type Dog struct {
}
func (d Dog) Eat() {
fmt.Println("狗在吃")
}
func (d Dog) Call() {
fmt.Println("狗在叫")
}
simplefactory_test.go
package DesignPatterns
import "testing"
func TestCat(t *testing.T) {
cat := NewAnimal("cat")
cat.Eat()
cat.Call()
}
func TestDog(t *testing.T) {
dog := NewAnimal("dog")
dog.Eat()
dog.Call()
}
测试结果
工厂方法模式
工厂方法模式使用子类的方式延迟生成对象到子类中实现,go中不存在继承,所以使用匿名组合来实现。每一个具体的类都会有自己的工厂类,每一个具体的类实现实际接口,工厂实现初始化实际类。
在这里OperatorBase是封装一个公用类。
factory.go
package DesignPatterns
//工厂模式
// 实际接口
type Operator interface {
SetA(int)
SetB(int)
Result() int
}
//工厂接口
type OperatorFactory interface {
Create() Operator
}
// Operator基类
type OperatorBase struct {
a int
b int
}
func (o *OperatorBase) SetA(a int) {
o.a = a
}
func (o *OperatorBase) SetB(b int) {
o.b = b
}
// 加法工厂类
type PlusOperatorFactory struct {
}
func (PlusOperatorFactory) Create() Operator {
return &PlusOperator{
OperatorBase: &OperatorBase{},
}
}
//加法实现
type PlusOperator struct {
*OperatorBase
}
func (o PlusOperator) Result() int {
return o.a + o.b
}
//减法工厂
type MinusOperatorFactory struct{}
func (MinusOperatorFactory) Create() Operator {
return &MinusOperator{
OperatorBase: &OperatorBase{},
}
}
//减法实现
type MinusOperator struct {
*OperatorBase
}
func (m MinusOperator) Result() int {
return m.a - m.b
}
factory_test.go
package DesignPatterns
import (
"fmt"
"testing"
)
// 计算
func compute(factory OperatorFactory, a, b int) int {
op := factory.Create()
op.SetA(a)
op.SetB(b)
return op.Result()
}
func TestOperator(t *testing.T) {
var (
factory OperatorFactory
)
factory = PlusOperatorFactory{}
if compute(factory, 1, 2) != 3 {
t.Fatal("error with factory")
}
factory = MinusOperatorFactory{}
if compute(factory, 4, 2) != 2 {
t.Fatal("error with factory")
}
}
测试结果