Golang设计模式之中介者模式

Jackey Golang 2,284 次浏览 , , 没有评论

创建文件CPU.go

package mediator

import "fmt"

type CPU struct {
    data string
}

func (c *CPU) Process(data string) {
    fmt.Println("CPU is running", data)
}

创建文件GPU.go

package mediator

import "fmt"

type GPU struct {
    data string
}

func (g *GPU) Display(data string) {
    fmt.Println("GPU is running", data)
}

创建文件MEM.go

package mediator

import "fmt"

type MEM struct {
    data string
}

func (m *MEM) Dump(data string) {
    fmt.Println("MEM is running", data)
}

创建文件Disk.go

package mediator

import "fmt"

type Disk struct {
    data string
}

func (d *Disk) Store(data string) {
    fmt.Println("disk is running", data)
}

创建文件Mediator.go

package mediator

type Mediator struct {
    Mcpu  *CPU
    Mgpu  *GPU
    Mdisk *Disk
    Mmem  *MEM
}

var mediator *Mediator

func GetMediatorInstance() *Mediator {
    if mediator == nil {
        mediator = &Mediator{}
    }
    return mediator
}

func (m *Mediator) Changed(i interface{}) {
    switch inst := i.(type) {
    case *CPU:
        m.Mcpu.Process(inst.data)
    case *GPU:
        m.Mgpu.Display(inst.data)
    case *Disk:
        m.Mdisk.Store(inst.data)
    case *MEM:
        m.Mmem.Dump(inst.data)
    default:

    }
}

main.go

package main

import mediator2 "test/design/mediator"

func main() {
    mediator := mediator2.GetMediatorInstance()
    mediator.Mcpu = &mediator2.CPU{}
    mediator.Mcpu.Process("hello")
    mediator.Mgpu.Display("hello")
    mediator.Mdisk.Store("hello")
    mediator.Mmem.Dump("hello")
    mediator.Changed(mediator.Mcpu)
    mediator.Mmem = &mediator2.MEM{}
    mediator.Changed(mediator.Mmem)
}

 

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go