Created
April 20, 2017 15:15
-
-
Save xigang/1993a7bbcfd8677a8492ff1f77bc7628 to your computer and use it in GitHub Desktop.
golang how to use interface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type StorageLogic interface { | |
Create(id int32) string | |
Delete(id int32) | |
} | |
type defaultStorageLogic struct{} | |
func NewStorageLogic() StorageLogic { | |
return (*defaultStorageLogic)(nil) | |
} | |
var storageHandler *Storage | |
type Storage struct { | |
StorageDriver StorageLogic | |
} | |
func NewStorageHandler() *Storage { | |
if storageHandler == nil { | |
storageHandler = &Storage{ | |
StorageDriver: NewStorageLogic(), | |
} | |
} | |
return storageHandler | |
} | |
var volume map[int32]string | |
func (p *defaultStorageLogic) Create(id int32) string { | |
volume = make(map[int32]string) | |
volume[id] = fmt.Sprintf("VolumeDriver%d", id) | |
return volume[id] | |
} | |
func (p *defaultStorageLogic) Delete(id int32) { | |
delete(volume, id) | |
} | |
func (p *Storage) CreateStorage(id int32) string { | |
return p.StorageDriver.Create(id) | |
} | |
func (p *Storage) DeleteStorage(id int32) { | |
p.StorageDriver.Delete(id) | |
} | |
func main() { | |
//第一种场景 | |
storageLogic := NewStorageLogic() | |
v := storageLogic.Create(1) | |
fmt.Println(v) | |
fmt.Println(volume) | |
storageLogic.Delete(1) | |
fmt.Println(volume) | |
//第二种场景 | |
storageHandler = NewStorageHandler() | |
v2 := storageHandler.CreateStorage(2) | |
fmt.Println(v2) | |
fmt.Println(volume) | |
storageHandler.DeleteStorage(2) | |
fmt.Println(volume) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment