If I understand this correctly, I would make separate static factory methods to 
create instances. It is easier / cleaner IMHO if you define your final objects 
as interfaces then you can supply different implementations depending on some 
state.

In my current project I'm making API interfaces for everything public and that 
gives me a very high amount of flexibility. I'm also using the old 
ServiceLoader to provide implementations. I'm also making a public static 
instance in interface called "use" that get inirialized using ServiceLoader. 
This can also supply different implementations depending on what is available 
on the classpath!

(Written with big thumbs on an iPhone ...)

Regards,
Tommy

______________________
Tommy Svensson
to...@natusoft.se
On 19 Apr 2024 at 18:32 +0200, o...@ocs.cz <o...@ocs.cz>, wrote:
> Hi there,
>
> I've bumped into a pretty trivial problem, but probably I've got a dumb day 
> today — can't find a solution :(
>
> How does one write a method which can be called either over an instance, or 
> over a class, in which case it would automatically use a default instance? 
> Like this, in pseudo-code which does not work in Groovy/Java, but shows 
> pretty well what I need:
>
> ===
> class Foo {
> static defaultInstance=new Foo()
> def foo() { ... does its stuff on this ... }
> static foo() { defaultInstance.foo() }
> }
> ===
> // usage when I happen to have the instance:
> Foo o= ...
> o.foo() // does its stuff on o
> // usage otherwise
> Foo.foo() // does its stuff on the default instance
> ===
>
> Thanks!
> OC

Reply via email to