Golang 模拟Java超类型(abstract class)的实现


golang中无继承概念,但利用golang匿名组合即可实现面向对象程序设计中继承的效果。在面向对象程序设计中,一般常见的两种超类型:接口,抽象类。在golang中,则更精简为只包含接口。在设计模式中,有要面向接口(超类型)编程这一重要的设计原则。在某些场合,抽象类比接口更便捷。但这不代表就必须使用抽象类,抽象类可用一般类组合接口来代替实现相应的效果。

下面就用golang接口来模拟java抽象类的实现。

java代码:

public abstract class PizzaStore {
    public Pizza orderPizza(String items) {
        Pizza pizza;
        pizza = createPizza(items);
        pizza.prepare();
        pizza.bake();
        pizza.cut();
        pizza.box();
        return pizza;
    }
    protected abstract Pizza createPizza(String items);
}

对应go代码:其中pizza.PizzaProduct相对应为java中返回的Pizza对象
type pizzaSaler interface {
    OrderPizza(string) pizza.PizzaProduct
    createPizza(string) pizza.PizzaProduct
}
                                                                       
type pizzaStore struct {
    psaler pizzaSaler
}
                                                                                   
func (this *pizzaStore) OrderPizza(items string) pizza.PizzaProduct {
    onePizza := this.psaler.createPizza(items)
    onePizza.Prepare()
    onePizza.Bake()
    onePizza.Cut()
    onePizza.Box()
    return onePizza
}

  golang的接口为非侵入式接口,为实现继承效果,pizzaStore子类应组合pizzaStore,并实现pizzaSaler的两个函数(OrderPizza方法已在父类PizzaStore实现,所以只要实现CreatePizza方法即可),把子类自身赋值给父类的psaler字段,这就类似与抽象类的子类必须实现抽象类(父类)中的抽象方法:

type NYPizzaStore struct {
    pizzaStore
}
                                                     
func (this *NYPizzaStore) createPizza(items string) pizza.PizzaProduct {
    if items == "cheese" {
        return pizza.NewNYStyleCheesePizza()
    } else if items == "veggie" {
        return pizza.NewNYStyleVeggiePizza()
    } else {
        return nil
    }
}
                                                                 
func NewNYPizzaStore() pizzaSaler {
    //golang无构造函数,故用此法建立实例并初始化
    return &NYPizzaStore{pizzaStore: pizzaStore{new(NYPizzaStore)}}
    //new(NYPizzaStore)将子类自身赋值给父类的pizzaSaler接口字段
}

Golang通过Thrift框架完美实现跨语言调用

golang里如何将一个struct指针转换成slice

Ubuntu 安装Go语言包

《Go语言编程》高清完整版电子书

Go语言并行之美 -- 超越 “Hello World”

我为什么喜欢Go语言

相关内容