问题描述
我经常看到对授权的引用,或Julia中的委托设计模式.
I see occational references to delegation,or the delegation design pattern in Julia.
这是什么?
例如我在
推荐答案
这是通过合成(而不是继承)实现的多态形式
This is a form of polymorphism via composition (rather than inheritance)
说一个具有包装器类型的包装器,包装了一个具体子类型AbstractT
的实例包装器本身应为AbstractT
的子类型(并非nesc总是正确的,而是总的来说.)
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).
要添加所有精确的子方法,例如AbstractT
的子类型,我们想委托这些方法中的某些或全部到包装的对象.我们通过元编程来做到这一点.如何执行此操作有一些变体.但是总的来说,提取是很难的模式,因此人们经常自己编写.
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.
说所有AbstractT
子类型都应实现 1arg length
,size
和mean
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.
这篇关于茱莉亚的代表团是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!