About - Angel's Blog.

ing
 
 
软件开发,程序设计,前端设计
 

About

 

This blog is licenced under a Creative Commons Licence Creative Commons Licence

Hello, everyone!

package main

import (
    "bytes"
    "context"
    "errors"
    "fmt"
    "reflect"
    "sync"
)

// define const
const (
    BLOG_NAME           = "Angel's Blog."
    NEXT                = "\n"
    DOT                 = "."
    ZERO                = 0
    ONE                 = 1
    EMPTY_STR           = ""
    BLANK_STR           = " "
    COMMA               = ","
    SEMICOLON           = ";"
    MAX_ANIMAL_CAPACITY = 5
    MAX_ANIMAL_AGE      = 10000
    END_OUT_STR         = "END_EOF"
)

// defined animal type
type AnimalType uint8

// defined animal enum
const (
    // no-one
    NONE = ZERO
    // human
    HUMAN AnimalType = NONE + iota
    // bird
    BIRD
    // fish
    FISH
)

// define global variables
var (
    // sync.mutex
    mutex sync.Mutex
    // sync.once
    once sync.Once
    // Deprecated: do-not direct-call this global variables
    myself *Human
    // arrays of animals ...
    animals []interface{}
)

// TODO defined interfaces START

// defined interfaces
type Introduce interface {
    // start first-introduction
    GetFirstIntroduction()
    // get intro
    GetIntro()
    // get hobbies
    GetHobbies()
    // get relate
    GetRelate()
    // get using-tools
    GetTools()
    // get contact-way
    GetContact()
    // EOF
    Eof()
    // End
    // @param ctx context
    // @return context.context instance
    End(ctx context.Context) context.Context
    // Out and print
    // @param ctx context
    Out(ctx context.Context)
}

// TODO defined interfaces END

// TODO defined struct START

// defined struct of animal
type Animal struct {
    Introduce `contains interface of [Introduce]`
    Name, Gender, Address string `defined base-attribute`
    Age                   uint16 `age...`
    Hobbies               []string `hobbies`
    Virgin                bool `was virgin?`
    writeBuff             *bytes.Buffer `defined buffer container`
    waitGroup             sync.WaitGroup `defined wait_group`
    eofChan               chan string `sealed message channel`
}

// defined struct of human
type Human struct {
    Animal `extends animal`
    Bio, ShortBio, QQ, QQGroup, Email string `defined all-attribute`
    Tools                             []string `tools`
}

// TODO defined struct END

// TODO defined normal method START

/**
    initial animals-container
    @param capacity capacity
 */
func initInjection(capacity uint8) {
    if animals != nil {
        return
    }
    animals = make([]interface{}, capacity, capacity)
}

/**
    injection this animal into array
    @param id injection `AnimalType`
    @param animal need injection of animal
    @return type of `Introduce`
 */
func injection(id AnimalType, animal interface{}) Introduce {
    mutex.Lock()
    if animals[id] == nil {
        animals[id] = animal
    }
    mutex.Unlock()
    return animals[id].(Introduce)
}

/**
    Dispatch goal of animal `GetIntro` method ...
    @param id injection `AnimalType`
 */
func Dispatch(id AnimalType) {
    animal := animals[id]
    if animal == nil || id > MAX_ANIMAL_CAPACITY {
        return
    }
    switch t := animal.(type) {
    default:
        t.(Introduce).GetIntro()
        break
    }
}

/**
    get method count, except special except_method_names
    @param object need reflect-operation object
    @param except_method_names need except method names
    @return method-count
 */
func getMethodCount(object interface{}, except_method_names ...string) int {
    t := reflect.TypeOf(object)
    dict := make(map[string]interface{})
    if wasEmpty(except_method_names) > ZERO {
        for h := ZERO; h < len(except_method_names); h++ {
            dict[except_method_names[h]] = DOT
        }
    }
    var count int
    for i := ZERO; i < t.NumMethod(); i++ {
        if dict[t.Method(i).Name] == nil {
            count++
        }
    }
    TruncateMap(dict)
    return count
}

/**
    this array was empty?
    @param arr dynamic-arguments
    @return (array-length)
 */
func wasEmpty(arr interface{}) int {
    if arr == nil {
        return ZERO
    }
    switch arr.(type) {
    case []string:
        return len(arr.([]string))
    }
    return ZERO
}

/**
    array to string, last-index-of-append with `,`
    @param buff bytes.buffer
    @param arr dynamic-arguments
 */
func arrayToString(buff *bytes.Buffer, arr interface{}) {
    if wasEmpty(arr) <= ZERO {
        return
    }
    range_arr := arr.([]string)
    arr_len := wasEmpty(range_arr)
    if arr_len <= ZERO {
        return
    }
    for index, value := range range_arr {
        buff.WriteString(value)
        if index < arr_len-ONE {
            buff.WriteString(COMMA)
        } else {
            buff.WriteString(SEMICOLON)
        }
        buff.WriteString(BLANK_STR)
    }
    buff.WriteString(NEXT)
}

// check-error
// @param err error
func CheckErr(err error) {
    if err != nil {
        fmt.Println(err)
        panic(err)
    }
}

/**
    truncate map
    @param dict truncated map
 */
func TruncateMap(dict map[string]interface{}) {
    for k, _ := range dict {
        delete(dict, k)
    }
}

// TODO defined normal method END

// TODO defined ONE_INSTANCE method START

// get only-once of human-instance
func GetHumanInstance() *Human {
    once.Do(func() {
        myself = &Human{
            Animal: Animal{
                Name:      "Angel",
                Gender:    "Male",
                Address:   "north-east of china",
                Age:       ,
                Hobbies:   []string{"Especially reading book", "Surfing the internet", "Google", "Twitter"},
                Virgin:    true,
                writeBuff: new(bytes.Buffer),
                waitGroup: sync.WaitGroup{},
                eofChan:   make(chan string),
            },
            Bio:      "http://www.0ee.com/",
            ShortBio: "http://j2.cc/",
            QQ:       "MzcwMDA0Mg==",
            QQGroup:  "MA==",
            Email:    "emhhaW5hbihhdClvdXRsb29rKGRvdCljb20=",
            Tools: []string{"Macbook Pro MD101(x2)", "TP-LINK TL-MR11U", "TP-LINK TL-WN821N", "Huawei ET188",
                            "Huawei E180", "Huawei EC169", "ITouch 4", "IPad 4(Cellular)", "Huawei A199",
                            "CubieBoard 1GB(ARM)", "CubieTruck 2GB", "Oculus Rift DK2",
                            "Google Glass 2(x2, white and blue)", "Google Nexus 5", "Nike Plus+", "JawBone Up2",
                            "Leap Motion"},
        }
        CheckErr(myself.Error())
    })
    return myself
}

// TODO defined ONE_INSTANCE method END

// TODO super-method START

// implements Error()
func (animal *Animal) Error() error {
    if animal.Age < MAX_ANIMAL_AGE {
        return nil
    }
    return errors.New("Maybe I'm living @ heaven ...")
}

// start first-introduction
func (animal *Animal) GetFirstIntroduction() {
    defer animal.waitGroup.Done()
    animal.writeBuff.WriteString(fmt.Sprintf("My name is %s, I’m %d years old, I come from %s.\n",
        animal.Name, animal.Age, animal.Address))
    animal.writeBuff.WriteString("My favourite color is white which makes people feel clear.\n")
}

// get hobbies
func (animal *Animal) GetHobbies() {
    defer animal.waitGroup.Done()
    hobbies_arr := animal.Hobbies
    if hobbies_arr == nil {
        return
    }
    animal.writeBuff.WriteString("In my leisure time, I have cultivated a lot of hobbies: ")
    arrayToString(animal.writeBuff, hobbies_arr)
}

// EOF
func (animal *Animal) Eof() {
    animal.eofChan <- animal.writeBuff.String()
    animal.writeBuff.Reset()
}

// End
// @param ctx context
// @return context.context instance
func (animal *Animal) End(ctx context.Context) context.Context {
    var local_ctx context.Context
    for {
        select {
        case eof_chan := <-animal.eofChan:
            local_ctx = context.WithValue(ctx, END_OUT_STR, eof_chan)
            goto close_channel
        }
    }
    // close channel ...
close_channel:
    {
        close(animal.eofChan)
    }
    return local_ctx
}

// Out and print
// @param ctx context
func (animal *Animal) Out(ctx context.Context) {
    println(ctx.Value(END_OUT_STR).(string))
}

// TODO super-method END

// TODO implements interface-methods START

// get human-intro
func (human *Human) GetIntro() {
    delta := getMethodCount(human, "Error", "GetIntro", "Eof", "End", "Out")
    human.waitGroup.Add(delta)
    human.GetFirstIntroduction()
    human.GetHobbies()
    human.GetRelate()
    human.GetContact()
    human.GetTools()
    human.waitGroup.Wait()
    human.Eof()
}

// get human-relate
func (human *Human) GetRelate() {
    defer human.waitGroup.Done()
    human.writeBuff.WriteString("Besides that, I have a happy family: father, mother and I.\n")
    human.writeBuff.WriteString("They care me a lot and I love them very much.\n")
    human.writeBuff.WriteString("I feel lucky to have such a family, this is my brief introduction of myself.\n")
    human.writeBuff.WriteString("That’s all, thank you very much!\n")
}

// get human-using-tools
func (human *Human) GetTools() {
    defer human.waitGroup.Done()
    tools_arr := human.Tools
    if tools_arr == nil {
        return
    }
    human.writeBuff.WriteString("Geek Equipment: ")
    arrayToString(human.writeBuff, tools_arr)
}

// get human-contact-way
func (human *Human) GetContact() {
    defer human.waitGroup.Done()
    human.writeBuff.WriteString(fmt.Sprintf("Blog URL: %s\nBlog Short URL: %s\nQQ: %s\nQQGroup: %s\nEmail: %s\n",
        human.Bio, human.ShortBio, human.QQ, human.QQGroup, human.Email))
}

// TODO implements interface-methods END

// main-method
func main() {
    // 1st
    initInjection(MAX_ANIMAL_CAPACITY)
    // 2nd
    const animal_type = HUMAN
    // injection ...
    var t = injection(animal_type, GetHumanInstance())
    // let's go!
    go Dispatch(animal_type)
    // receive message and close this channel!
    t.Out(t.End(context.Background()))
}

 



或者通过RSS 关注本站的更新 ^ O ^ 。” —  by  转载请注明:来自 Angel's Blog.
本文永久链接: http://www.0ee.com/about
 
  • QQ书签
  • Del.icio.us
  • 百度收藏
  • Google
  • 饭否
  • FriendFeed
 
本文的评论功能被关闭了.
 
 
  • 正在加载...