问题
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