design-patterns - What is delegation in julia?
问题描述
I see occational references to delegation, or the delegation design pattern in Julia.
What is this?
E.g. I see it mentioned in
解决方案
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.
推荐阅读
- react-native - 如何运行特定的 fastlane 任务,例如“pilot”
- amazon-s3 - 通过 Lambda 和 API Gateway 从 AWS S3 下载图像——使用 fetch 类
- javascript - Storybook React 及其示例组件不起作用
- python - 在 python 中,如果 y==0 则做一些事情,如果 y!=0 则做其他事情
- c - 为什么到达 MEX 文件的最后一行后返回 Matlab 需要这么长时间?
- symfony - symfony 在规范化实体时找不到支持规范化器
- c - 为什么下面的代码会在字符串末尾执行意外的字母?
- javascript - 链 connect/mapStateToProps/mapDispatchToProps 函数用于 react-redux 中的代码重用
- java - 你如何在java中重复初始化一个新标签?
- java - @MatrixVariable 注解的 pathVar 属性在 Spring 中是如何工作的?