如何使一个 class 中的方法可从另一个访问?

How to make methods in one class accessible from another one?

我是埃菲尔铁塔的初学者。我有 2 classes。主叫APPLICATION:

class
    APPLICATION

inherit
    ARGUMENTS

create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        do
            print ("test")
        end    
end

另一个 class 叫 BLUE:

class
    BLUE
create
    make

feature
    make
        local
            dead:BOOLEAN
            active:BOOLEAN
            number:BOOLEAN

        do
            io.putstring ("writetest")
        end

end

我想知道如何使 BLUE class 中的方法可以从 APPLICATION class 访问和调用?

在classAPPLICATION中,可以添加一个BLUE类型的局部变量b,然后调用make作为其创建过程:

make
    local
        b: BLUE
    do
        create b.make
    end

一般来说,在面向对象语言中 class 之间有两种关系允许一个 class 访问另一个 class 的特性:

  1. 继承,
  2. 客户-供应商关系。

在第一种情况下,class 继承了父项的所有特征,并且可以将它们称为自己的特征:

class APPLICATION

inherit
    BLUE
        rename
                -- Class `APPLICATION' has `make' as well,
                -- so the inherited one has to be renamed to avoid a clash.
            make as make_blue
        end

create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        do
                -- This prints "test".
            print ("test")
                -- Call the inherited feature `{BLUE}.test'
                -- renamed above into `make_blue'
                -- that prints "writetest".
            make_blue
        end

end

在继承的情况下,对同一个对象进行调用。

在客户-供应商关系中,调用是在不同的对象上执行的。在您的示例中,要调用的功能与创建过程一致,因此调用成为正在创建的对象的创建指令的一部分:

class APPLICATION

create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        local
            other: BLUE
        do
                -- This prints "test".
            print ("test")
                -- Create an object of type `BLUE'
                -- calling its creation procedure `make'
                -- that prints "writetest".
            create other.make
        end

end

关于何时使用一种方法而不是另一种方法的粗略近似如下。我们可以将继承视为 "is-a",将客户-供应商视为 "has" 关系。例如,苹果有颜色,但它不是颜色,所以客户与供应商的关系更适合。另一方面是水果,继承关系比较契合。在后一种情况下,苹果 class 通过指定一些其他属性(如形状和种子位置)来改进水果 class。但它无法细化颜色 class。与您的示例相同:它看起来不像 APPLICATIONBLUE 的示例,因此客户与供应商的关系似乎更合适。

首先,在BLUE中你需要一个方法,你不应该写在create方法中,这样会增加你写程序的难度。特别是随着程序变得越来越复杂。所以我添加了 write_message 它不是创建方法。

class
    BLUE

feature
    write_message
        local
            dead:BOOLEAN
            active:BOOLEAN
            number:BOOLEAN
        do
            io.putstring ("writetest")
        end
end

现在,我们需要调用新方法

class
    APPLICATION   
inherit
    ARGUMENTS
create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        local
             blue: BLUE
        do
            print ("test")
            create blue
            blue.write_message
        end
end