繁体   English   中英

埃菲尔铁塔:在运行时创建类型化的对象

[英]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

create {ZOO_SECTOR[animal.item.generating_type]} l_sector ,编译器与我不同意,我尝试使用l_type: TYPE[ANIMAL]create {ZOO_SECTOR[l_type]} l_sector 我有义务做类似的事情吗? 对我来说,这与多态性灵活性矛盾,我想我错过了一种机制/陈述

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类型系统依赖于类结构,并且类结构在编译时是固定的。 可能可以动态添加类型(例如,应该可以使用反射来提出解决方案),但这不能在语言本身中直接表达。

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

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

给予ZOO_SECTOR [LION]为类型的项目LION

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM