Go语言程序设计(三)

对象池模式

The object pool creational design pattern is used to prepare and keep multiple instances according to the demand expectation.

实例:

package main

import (
	"fmt"
	"strconv"
	"time"
)

type Pool chan *Object

type Object struct {
	name string
}

func New(total int) *Pool {
	p := make(Pool, total)
	for i := 0; i < total; i++ {
		p <- &Object{name:strconv.Itoa(i)}
	}
	return &p
}

func main() {
	p := New(2)
	for {
		select {
		case obj := <- *p:
			fmt.Println(obj.name)
			//time.Sleep(2*time.Second)
			*p <- obj
			time.Sleep(1*time.Second)
			//default:
			//	return
		}
	}

}

  

Builder Pattern 建造者模式

  Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.
In Go, normally a configuration struct is used to achieve the same behavior, however passing a struct to the builder method fills the code with boilerplate if cfg.Field != nil  {...} checks.
实例代码:
package main

import "fmt"

// 创建speed类型
type Speed float64
const (
	MPH Speed = 1
	KPH       = 1.60934
)

// 创建颜色类型
type Color string
const (
	BlueColor  Color = "blue"
	GreenColor       = "green"
	RedColor         = "red"
)

// 创建轮胎类型
type Wheels string
const (
	SportsWheels Wheels = "sports"
	SteelWheels         = "steel"
)

// 创建car需要的工序,最后通过build创建
type Builder interface {
	Color(Color) Builder
	Wheels(Wheels) Builder
	TopSpeed(Speed) Builder   // 创建属性
	Build() Interface  // 创建动作
}

// 返回的接口体具备如下方法
type Interface interface {
	Drive() error
	Stop() error
}

type Car struct {
	Name string
	Wheel Wheels
	Speeds Speed
	Colors Color
}
// 返回一个car实例的接口
func NewBuilder() Builder {
	return &Car{  // 必须是指针,因为后面的函数都是使用指针,只有指针的Car才能调用所有实现了的方法
		Name:   "",
		Wheel:  "",
		Speeds: 0,
		Colors: "",
	}
}

// Builder接口实现
func (p *Car) Color(color Color) Builder{
	p.Colors = color
	return p
}

func (p *Car) Wheels(Wheel Wheels) Builder{
	p.Wheel = Wheel
	return p
}

func (p *Car) TopSpeed(S Speed) Builder{
	p.Speeds = S
	return p
}

func (p *Car) Build() Interface {
	return p
}

func (p *Car) Drive() error {
	fmt.Println("I'm running...",p.Speeds,p.Speeds,p.Wheel,p.Colors)
	return nil
}

func (p *Car) Stop() error {
	fmt.Println("I'm stopping...",p.Name,p.Speeds,p.Wheel,p.Colors)
	return nil
}

func main() {
	// 通过链式编程来给实例的过程赋值属性和动作,需要注意的是,这些都是通过接口的方式进行约束,所以必须实现。
	car := NewBuilder().Color(BlueColor).Wheels(SportsWheels).TopSpeed(MPH).Build()
	car.Drive()
}

  

Factory Method Pattern 工厂化方法模式

Factory method creational design pattern allows creating objects without having to specify the exact type of the object that will be created. 工厂方法创建设计模式允许创建对象,而不必指定将要创建的对象的确切类型。根据不同的情况创建不同的对象方法

代码如下:

package main

import (
	"bufio"
	"fmt"
	"strings"
)

type StorageType int
const (
	MemoryStorage StorageType = 1 << iota
	TempStorage
)

type Store interface {
	Open(string) (error)
}

type MemoryStorages struct {
	data string
}

func newMemoryStorage(s string) *MemoryStorages {
	return &MemoryStorages{data: s}
}

func (p *MemoryStorages) Open(s string) error {
	sr := strings.NewReader(p.data)
	r := bufio.NewReader(sr)
	line, _, err := r.ReadLine()
	if err != nil {
		return err
	}
	fmt.Println(string(line))
	return nil
}

type TempStorageS struct {
	data string
}

func newTempStorage(s string) *TempStorageS {
	return &TempStorageS{data:s}
}

func (p *TempStorageS) Open(s string) error {
	sr := strings.NewReader(p.data)
	r := bufio.NewReader(sr)
	line, _, err := r.ReadLine()
	if err != nil {
		return err
	}
	fmt.Println(line)
	return nil
}

// 根据定义的类型,传入不同的参数创建不同的对象实现方法
func NewStore(t StorageType) Store {
	switch t {
	case MemoryStorage:
		return newMemoryStorage("Memory\n....")
	case TempStorage:
		return newTempStorage("openfile")
	default:
		return newMemoryStorage("default\n....")
	}
}

func main() {
	memory := NewStore(1)
	memory.Open("start")
}

  

猜你喜欢

转载自www.cnblogs.com/double-W/p/12791392.html