golang中无继承概念,但利用golang匿名组合即可实现面向对象程序设计中继承的效果。在面向对象程序设计中,一般常见的两种超类型:接口,抽象类。在golang中,则更精简为只包含接口。在设计模式中,有要面向接口(超类型)编程这一重要的设计原则。在某些场合,抽象类比接口更便捷。但这不代表就必须使用抽象类,抽象类可用一般类组合接口来代替实现相应的效果。
下面就用golang接口来模拟java抽象类的实现。
java代码:
1
2
3
4
5
6
7
8
9
10
11
12
|
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对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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字段,这就类似与抽象类的子类必须实现抽象类(父类)中的抽象方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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接口字段
}
|
本文转自 ponpon_ 51CTO博客,原文链接:http://blog.51cto.com/liuxp0827/1353140,如需转载请自行联系原作者