创建型模式
对象实例化的模式,创建型模式用于解耦对象的实例化过程
工厂模式
package main
import "fmt"
// 产品接口
type Shape interface {
draw()
}
//具体产品
type Rectangle struct {
}
func (Rectangle) draw() {
fmt.Println("Draw Rectangle")
}
type Square struct {
}
func (Square) draw() {
fmt.Println("Draw Square")
}
type Circle struct {
}
func (Circle) draw() {
fmt.Println("Draw Circle")
}
//工厂
type ShapeFactory struct {
}
func (*ShapeFactory) createShape(shape string) Shape {
if shape == "Rectangle" {
return &Rectangle{}
} else if shape == "Square" {
return &Square{}
} else if shape == "Circle" {
return &Circle{}
}
return nil
}
/*
if the type T conforms to a protocol,
then the corresponding pointer type *T also conforms to the protocol,
since a type's method set is included in its pointer type's method set.
*/
func main(){
f := new(ShapeFactory)
s := f.createShape("Square")
s.draw()
}
行为型模式
类和对象如何交互,及划分责任和算法
责任链模式
package main
import "fmt"
// 处理器接口
type SensitiveWordDetector interface {
detect(content string) bool
}
// 责任链
type SensitiveWordDetectorChain struct {
detectors []SensitiveWordDetector
}
// 添加处理器
func (c *SensitiveWordDetectorChain) addDetector(detect SensitiveWordDetector) {
c.detectors = append(c.detectors, detect)
}
// 处理入口
func (c *SensitiveWordDetectorChain) detect(content string) bool {
for _, detect := range c.detectors{
if detect.detect(content){
return true
}
}
return false
}
// 具体处理器
type AdSensitiveWordDetector struct {}
func (*AdSensitiveWordDetector) detect(content string) bool {
// details
return true
}
type PoliticalWordDetector struct {}
func (*PoliticalWordDetector) detect(content string) bool {
// details
return false
}
func main(){
chain := &SensitiveWordDetectorChain{}
chain.addDetector(&AdSensitiveWordDetector{})
chain.addDetector(&PoliticalWordDetector{})
res := chain.detect("test")
fmt.Println(res)
}
结构型模式
把类或对象结合在一起形成一个更大的结构