What is delegation in julia?

蓝咒 提交于 2021-02-08 11:11:17

问题


I see occational references to delegation, or the delegation design pattern in Julia.

What is this?

E.g. I see it mentioned in

  • This file in DataStructures.jl

回答1:


This is a form of polymorphism via composition (rather than inheritance)

Say one has a wrapper type, wrapping some instance of a concrete subtype of AbstractT where the wrapper itself is intended to be a subtype of AbstractT (Not nesc always true, but in general).

To add all the methods one exacts such a subtype of AbstractT to have, we want to delegate some or all of those methods to the wrapped object. We do this via metaprogramming. There are a few varients on how to do this. But in general it is a hard pattern to abstract so people often write their own.

Say that that all AbstractT subtypes should implement 1arg length, size and mean

struct WrappedT{T<:AbstractT} <: AbstractT
    backing ::T
    ...
end

for fun in (:(Base.length), :(Base.size), :(Statistics.mean))
    @eval ($fun)(x::WrappedT, args...) = ($fun(x.backing, args...))
end

Generally you won't delegate all the methods, since some you will want to do differently, that is the point of creating the new type after all.



来源:https://stackoverflow.com/questions/54789937/what-is-delegation-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!