interface是一种类型 。一个对象的行为规范,只定义规范不实现,由具体的对象来实现规范的细节。
工厂方法模式:
一种类型多种接口
type sayer interface {
say ()
}
type mover interface {
move()
}
type fooder interface {
food()
}
type dog struct {
name string
}
func (d dog ) say() {
fmt.Println("说话:",d.name)
}
func (d dog) move(){
fmt.Println("移动: ",d.name)
}
func (d * dog) food (){
fmt.Println( "食物:",d.name)
}
func main() {
var x sayer
var y mover
var z fooder
a := dog{name: "hello",}
x = a
x.say()
b := dog{name: "shanghai",}
y = b
y.move()
c := dog{name: "gouliang",}
z = &c
z.food()
}
多种类型一种接口:
type mover interface {
Move()
}
type dog struct {
}
type car struct {
}
func (d dog) Move(){
fmt.Println("百公里加速,只要一碗饭")
}
func (c car ) Move(){
fmt.Println("百公里加速,只要一箱油")
}
func main() {
var x mover
x = dog{}
x.Move()
x = car{}
x.Move()
}
接口可以使用断言来进行判断:
func justifyType(x interface{}){
switch v := x.(type){
case string:
fmt.Printf("x is a string,value is %v\n", v)
case int:
fmt.Printf("x is a int is %v\n", v)
case bool:
fmt.Printf("x is a bool is %v\n", v)
default:
fmt.Println("unsupport type!")
}
}
空接口判断:
对比有值的
抽象工厂模式:
1.游戏颜色:
// 颜色接口
type Color interface {
Color() string
}
// 粉红色主题颜色
type PinkColor struct {
}
func (p *PinkColor) Color() string {
return "pink"
}
// 蓝色主题颜色
type BlueColor struct {
}
func (b *BlueColor) Color() string {
return "blue"
}
2.游戏声音:
// 声音接口
type Voice interface {
Voice() string
}
// 女孩声音
type GirlVoice struct {
}
func (g *GirlVoice) Voice() string {
return "girl"
}
// 男孩声音
type BoyVoice struct {
}
func (b *BoyVoice) Voice() string {
return "boy"
}
3.不同主题:认真看,这里面的返回值很有趣
type ThemeFactory interface {
GetVoice() Voice
GetColor() Color
}
// 女生主题
type GirlTheme struct {
}
func (g *GirlTheme) GetVoice() Voice {
return new(GirlVoice)
}
func (g *GirlTheme) GetColor() Color {
return new(PinkColor)
}
// 男生主题
type BoyTheme struct {
}
func (b *BoyTheme) GetVoice() Voice {
return new(BoyVoice)
}
func (b *BoyTheme) GetColor() Color {
return new(BlueColor)
}
执行看一下效果吧:
func main() {
girlTheme := new(GirlTheme)
if girlTheme.GetColor().Color() != "pink" || girlTheme.GetVoice().Voice() != "girl" {
fmt.Println("GirlTheme error")
}
// 实例化男生主题
boyTheme := new(BoyTheme)
if boyTheme.GetColor().Color() != "blue" || boyTheme.GetVoice().Voice() != "boy" {
fmt.Println("BoyTheme error")
}
fmt.Println("以上函数的不等式都成立,不信可以把 != 换成 ==")
}