主要用于针对某些行为的策略选择,减少多次类型断言或者判断
栗子:利用云厂商的cos进行文件存储时,希望A类型的文件上传到腾讯云;B类型的文件上传到阿里云。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| type BucketStrategy interface { upload(ctx context.Context, file string) error }
var buckets = map[string]BucketStrategy{ "tencent": &tencentBucket{}, "ali": &aliBucket{}, }
func NewBucketStrategy(b string) (BucketStrategy, error) { s, ok := buckets[b] if !ok { return nil, fmt.Errorf("not found bucket %s", b) } return s, nil }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| type tencentBucket struct{}
func (t *tencentBucket) upload(ctx context.Context, file string) error { panic("implement me") }
type aliBucket struct{}
func (a *aliBucket) upload(ctx context.Context, file string) error { panic("implement me") }
|
如上就实现了策略选择的一个大致框架,在使用时只需要判断好文件类型即可,如下:
1 2 3 4 5 6 7 8 9 10
| func TestBucketStrategy(t *testing.T) { bucket := getFileType("B") bucketStrategy, _ := NewBucketStrategy(bucket) _ = bucketStrategy.upload(context.Background(), "localPath") }
func getFileType(file string) string { if file == "A" {return "tencent"} return "ali" }
|