2014-10-02 91 views
2

我有一個接口:對於給定的接口,我有三個實現。這三種實現如何共享相同的方法?

type Reader interface { 
    // Read IV and Master header 
    ReadMaster(p []byte, full bool) (int, error) 

    // Read User header 
    ReadUser(p []byte, full bool) (int, error) 

    // Read Content data 
    ReadContent(p []byte) (int, error) 
} 

而且我有三個struct S跟接口兼容。所有三個結構都有samve方法ReadUser。所以我必須這樣做:

func (r *s1) ReadUser(buf []byte, full bool) (int, error) { 
//.... code 1 .... 
} 
func (r *s2) ReadUser(buf []byte, full bool) (int, error) { 
//.... code 2 .... 
} 
func (r *s3) ReadUser(buf []byte, full bool) (int, error) { 
//.... code 3 .... 
} 

但是,上面的「code1」,「code2」和「code3」完全一樣。有減少重複代碼的好方法嗎?例如。定義一次函數並將其分配給三個結構?

回答

7

用它自己的類型包裝它。還記得Go中的接口應該只爲小型特定任務提供合同。一個接口只包含一種方法是很常見的。

type UserReader interface { 
    ReadUser(p []byte, full bool) (int, error) 
} 

type UserRepo struct { 
} 

的方法添加到該類型:

func (ur *UserRepo) ReadUser(p []byte, full bool) (int, error) { 
    // code to read a user 
} 

然後,將它嵌入到你的其他類型:

type s1 struct { 
    *UserRepo 
    // other stuff here.. 
} 

type s2 struct { 
    *UserRepo 
    // other stuff here.. 
} 

type s3 struct { 
    *UserRepo 
    // other stuff here.. 
} 

然後,您可以:

u := s1{} 
i, err := u.ReadUser(..., ...) 

u2 := s2{} 
i2, err2 := u2.ReadUser(..., ...) 

// etc.. 

..你也可以這樣做:

doStuff(u) 
doStuff(u2) 

..其中doStuff是:

func doStuff(u UserReader) { 
    // any of the three structs 
} 

Click here to see it in the Playground

相關問題