组成和多重继承

时间:2012-06-21 23:32:20

标签: inheritance interface go composition

由于Go使用合成系统而不是(多重)继承,我只是想知道这3个代码片段。 Go说它们迫使程序员使用组合。

A)应该(几乎)正确的Go-Code, B)伪 C)伪

Imho结果在所有三个代码上总是相同的,除了事实,B)和C)可以用于更多的东西和A)强迫你坚持组合?

即使你假设B)在类中没有sort-method但是 - 让我们说像A这样的全局不会产生真正的差别oO

A)转码:

interface Sort
    Len()
    Less(i, j int) bool
    Swap(i, j int)

func (qs *Sort) sort()
    doTheSorting

type MyData struct {
    var value int
}

func (s *MyData) Len() { ... }
func (s *MyData) Less(i, j int) bool { ... }
func (s *MyData) Swap(i, j int) { ... }

B)看起来像继承,但根据编译器的工作原理,它可以被视为嵌入式。

class Sort

    public sort() { ... }

    abstract Len()
    abstract Less(i, j int) bool
    abstract Swap(i, j int)

C)

interface SortInterface
    void Len()
    bool Less(i, j int)
    void Swap(i, j int)

class Sort implements SortInterface
    public sort() { ... }

用法B和C:

class MyClass **embed** Sort

    int value

    void Len() { ... }
    bool Less(i, j int) { ... }
    void Swap(i, j int) { ... }

1 个答案:

答案 0 :(得分:4)

不,这不是怎么回事。以下是可以排序的类型的示例(从标准库中提取)。

type IntSlice []int

func (p IntSlice) Len() int           { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

这实现了接口:

// Name of interface changed for clarity
type Sort interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

实现Sort接口的类型不会获得新方法。您无法将方法分配给界面,例如示例func (qs *Sort) sort() {...}

但是,允许将其传递给期望类型为Sort的变量的函数和方法。因此,我可以调用sort.Sort(myIntSlice)然后对其进行排序。

这是一个示例函数,它接受任何实现Sort接口的参数:

func IsSorted(data Sort) bool {
    n := data.Len()
    for i := n - 1; i > 0; i-- {
        if data.Less(i, i-1) {
            return false
        }
    }
    return true
}

IsSorted中,函数不知道真正的数据类型是什么。它可能是IntSlice或其他任何内容。它所知道的是,你给它的任何参数都实现了Sort接口中的方法。

我似乎无法弄清楚你问的问题。另外,伪代码很难理解。使用另一种语言如java会更好。

相关问题