1. 程式人生 > >簡單工廠模式的go程式碼示例

簡單工廠模式的go程式碼示例

       簡單工廠模式很簡單,工廠負責生產物件, 來看下:

package main

import (
    "fmt"
)

type BaseIntf interface { 
    Operate(int, int) int
}


type AddOperate struct {}

func (this *AddOperate)Operate(rhs int, lhs int)  int {
    return rhs + lhs
}

type SubOperate struct {}

func (this *SubOperate)Operate(rhs int, lhs int) int {
    return rhs - lhs
}


func CreateOperate(operatename string) BaseIntf {
    switch   operatename {
        case "+":
            return &AddOperate{}
        case "-":
            return &SubOperate{}
        default:
            panic("invalid")
            return nil
    }
}


func main() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println(err)
        }
    }()
    var op BaseIntf 
    fmt.Printf("%v,%T\n", op, op)

    op = CreateOperate("+") 
    fmt.Printf("%T\n", op)
    fmt.Printf("add: %d\n", op.Operate(1,2)) 

    op = CreateOperate("-") 
    fmt.Printf("%T\n", op)
    fmt.Printf("sub: %d\n", op.Operate(1,2)) 
    return
}

          結果:

<nil>
*main.AddOperate
add: 3
*main.SubOperate
sub: -1

 

       不多說。