Eiffel:在运行时创建类型化对象

Eiffel: create at runtime a typed object

尝试创建一个由@runtime 决定的对象我有类似的情况:

class ZOO

feature

    animals: LINKED_LIST[ANIMAL]

    default_create
        do
            create animals.make
            animals.extend(create {LION})
            animals.extend(create {SERPENT})
            animals.extend(create {BIRD})
        end

    open
        local
            l_sector: ZOO_SECTOR[ANIMAL]
        do
            across
                animals as animal
            loop
                create {ZOO_SECTOR[animal.item.generating_type]} l_sector
            end
        end

on create {ZOO_SECTOR[animal.item.generating_type]} l_sector 编译器不同意我的意见,我尝试了 l_type: TYPE[ANIMAL]create {ZOO_SECTOR[l_type]} l_sector 都不起作用。 我有义务做那样的事情吗?这对我来说与多态性灵活性相矛盾,我想我错过了 mecanism/statement

open
    local
        l_sector: ZOO_SECTOR[ANIMAL]
    do
        across
            animals as animal
        loop
            if attached {LION} animal.item then
                create {ZOO_SECTOR[LION]} l_sector
            else if attached {SERPENT} animal.item then
                create {ZOO_SECTOR[SERPENT]} l_sector
            else
                .....
        end
    end

Eiffel 类型系统依赖于class 结构,而class 结构在编译时是固定的。动态添加类型是可能的(例如,应该可以使用反射提出解决方案),但这不能直接用语言本身表达。

如果允许动物知道其动物园区域,则 ZOO_SECTOR 类型可以直接在动物中编码 class:

class ANIMAL feature ...
    sector: ZOO_SECTOR [like Current] do create Result end
end

由于使用了like Current,后代中无需添加任何新代码。示例中的循环将变为

across
    animals as animal
loop
    l_sector := animal.item.sector
end

LION 类型的项目提供 ZOO_SECTOR [LION],等等