github.com/kaydxh/golang@v0.0.131/tutorial/programming_paradigm/factory_test.go (about) 1 package tutorial 2 3 import ( 4 "context" 5 "fmt" 6 "testing" 7 "time" 8 9 "github.com/go-playground/validator/v10" 10 ) 11 12 type FactoryConfigFunc func(c *FactoryConfig) error 13 14 type FactoryConfig struct { 15 Validator *validator.Validate 16 Addr string 17 Timeout time.Duration //接口处理超时时间 18 } 19 20 func (fc *FactoryConfig) ApplyOptions(configFuncs ...FactoryConfigFunc) error { 21 22 for _, f := range configFuncs { 23 err := f(fc) 24 if err != nil { 25 return fmt.Errorf("failed to apply factory config, err: %v", err) 26 } 27 } 28 29 return nil 30 } 31 32 func (fc FactoryConfig) Validate() error { 33 valid := fc.Validator 34 if valid == nil { 35 valid = validator.New() 36 } 37 return valid.Struct(fc) 38 } 39 40 func (fc FactoryConfig) Do(ctx context.Context) error { 41 fmt.Println("done") 42 return nil 43 } 44 45 type Factory struct { 46 fc FactoryConfig 47 } 48 49 func NewFactory(fc FactoryConfig, configFuncs ...FactoryConfigFunc) (Factory, error) { 50 err := fc.ApplyOptions(configFuncs...) 51 if err != nil { 52 return Factory{}, err 53 } 54 55 err = fc.Validate() 56 if err != nil { 57 return Factory{}, err 58 } 59 60 return Factory{fc: fc}, nil 61 } 62 63 func (f Factory) NewRepository(ctx context.Context) (Repository, error) { 64 //the Repository can also not FactoryConfig instance 65 // the example use FactoryConfig 66 return f.fc, nil 67 } 68 69 type Repository interface { 70 Do(ctx context.Context) error 71 } 72 73 func (f Factory) Do(ctx context.Context) error { 74 return f.fc.Do(ctx) 75 } 76 77 func TestFactroy(t *testing.T) { 78 factory, err := NewFactory(FactoryConfig{ 79 Addr: "localhost:10001", 80 Timeout: 5 * time.Second, 81 }) 82 if err != nil { 83 t.Errorf("failed to new factory, err: %v", err) 84 } 85 86 ctx := context.Background() 87 repository, err := factory.NewRepository(ctx) 88 if err != nil { 89 t.Errorf("failed to new repository, err: %v", err) 90 } 91 err = repository.Do(ctx) 92 if err != nil { 93 t.Errorf("failed to call Do method, err: %v", err) 94 } 95 }