Go语言设计模式(五)

Generator Pattern 生成器模式

Generators yields a sequence of values one at a time. 生成器一次生成一个值序列。
package main

import "fmt"

func Count(start int, end int) chan int {
	ch := make(chan int)
	go func(ch chan int) {
		for i := start; i <= end; i++{
			ch <- i
		}
		close(ch)  // 需要关闭channel,否则监听这个生成器的协程无法关闭
	}(ch)
	return ch
}

func main() {
	for i := range Count(1,99) {
		fmt.Println("Pass it around, put one up,",i,"bottles of beer on the wall")
	}

	fmt.Println(100,"bottles of beer on the")
}

Parallelism Pattern 并行模式

Parallelism allows multiple "jobs" or tasks to be run concurrently and asynchronously. 并行性允许多个“作业”或任务并发和异步运行
An example showing implementation and usage can be found in parallelism.go.  一个显示实现和使用的例子可以在parallel .go中找到。
 
Fan-In Messaging Patterns
Fan-In is a messaging pattern used to create a funnel for work amongst workers (clients: source, server: destination).  We can model fan-in using the Go channels.  扇入是一种消息传递模式,用于在工作者(客户端:源,服务器:目标)之间创建工作漏斗。我们可以使用Go通道来模拟扇入。
package main

import (
	"fmt"
	"sync"
)

func Merge(cs ...<-chan int) <-chan int {
	var wg sync.WaitGroup

	out := make(chan int)

	send := func(c <-chan int) {
		for n := range c {
			out <- n
		}
		wg.Done()
	}
	wg.Add(len(cs))

	for _, c := range cs {
		go send(c)
	}


	go func() {
		wg.Wait()
		close(out)
	}()
	return out
}

func main() {
	c := make(chan int, 2)
	d := make(chan int, 2)
	c <- 4
	c <- 5
	d <- 6
	d <- 7

	m := Merge(c, d)
	for i := range m {
		fmt.Println(i)
	}
}

 
装饰器模式
package main

import (
	"fmt"
	"log"
	"net/http"
)

func isAuthorized(endpoint func(http.ResponseWriter, *http.Request)) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		fmt.Println("Checking to see if Authorized header set...")

		if val, ok := r.Header["Authorized"]; ok {
			fmt.Println(val)
			if val[0] == "true" {
				fmt.Println("Header is set! We can serve content!")
				endpoint(w, r)
			}
		} else {
			fmt.Println("Not Authorized!!")
			fmt.Fprintf(w, "Not Authorized!!")
		}
	})
}

func homePage(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Endpoint Hit: homePage")
	fmt.Fprintf(w, "Welcome to the HomePage!")
}

func handleRequests() {

	http.Handle("/", isAuthorized(homePage))
	log.Fatal(http.ListenAndServe(":8081", nil))
}

func main() {
	handleRequests()
}

 

相关推荐