zoukankan      html  css  js  c++  java
  • golang 简单工厂模式

    package kit
    
    
    //golang简单工厂模式
    //go 语言没有构造函数一说,所以一般会定义NewXXX函数来初始化相关类。 NewXXX 函数返回接口时就是简单工厂模式,也就是说Golang的一般推荐做法就是简单工厂。
    //在这个simplefactory包中只有API 接口和NewAPI函数为包外可见,封装了实现细节。
    import "fmt"
    
    type API interface {
    	Say(name string) string
    }
    
    var NEW = func (t int) API{
    	if t == 1{
    		return &hiAPI{}
    	}else if t == 2{
    		return &helloAPI{}
    	}
    	return nil
    }
    
    type hiAPI struct{}
    func (*hiAPI) Say(name string) string{
    	return fmt.Sprintf("Hi,%s",name)
    }
    
    type helloAPI struct{}
    func (*helloAPI) Say(name string) string{
    	return fmt.Sprintf("hello,%s",name)
    }
    

      

    package kit
    
    
    import (
    	"testing"
    
    )
    
    func TestType1(t *testing.T) {
    	api := NEW(1)
    	a := api.Say("tom")
    	if a != "Hi,tom"{
    		t.Fatal("Type1 test fail")
    	}
    }
    

      

  • 相关阅读:
    python 对比学习
    支付宝
    springboot logback
    ngnix学习视频
    node学习
    puppeteer 相关知识
    Dota2App--第三天
    Dota2APP--第二天
    Dota2APP--第一天
    iOS ---进阶之摇一摇
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/12856090.html
Copyright © 2011-2022 走看看