I played around with this a few years ago in github.com/MasonProtter/PatternDispatch.jl
julia> module PatternFruitFactory
using PatternDispatch
abstract type Fruit end
struct Apple <: Fruit end
struct Orange <: Fruit end
@pattern fruit("apple") = Apple()
@pattern fruit("orange") = Orange()
@pattern fruit(s) = error("unknown fruit $s")
end
julia> @btime PatternFruitFactory.fruit("orange")
3.449 ns (0 allocations: 0 bytes)
Main.PatternFruitFactory.Orange()
These are extensible at a later time:
julia> @btime PatternFruitFactory.fruit("banana")
7.537 ns (0 allocations: 0 bytes)
Main.PatternFruitFactory.Banana()
PatternDispatch.jl does some stuff that's unfriendly to precompilation though so it doesn't fit very well into packages. Very much just a proof of concept.