groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From OC <>
Subject Re: Hierarchy of singletons howto?
Date Fri, 01 Apr 2016 19:38:43 GMT
At least one of us two must have missed something in Object-Oriented-101.

There is exactly one instance of class Foo.

And there is exactly one instance of class Bar, whose functionality is derived from Foo.

Consider the factory pattern: there are two related classes, A and B extends A. If it so happens
that each of them needs a factory class, then is is self-evident that

(a) both AFactory and BFactory need to be singletons (as any factory out there)
(b) BFactory should extend AFActory, for just as B's functionality extends A's functionality,
the same applies for their factories.

And one can implement the functionality easily, e.g., using

class Foo {
  static instance=newInstance()
class Bar extends Foo {
  static instance=newInstance()

it works like a charm, only -- unlike @Singleton -- it is not lazy (and if turned to lazy,
it would not be threadsafe).

Thanks and all the best,

On 1. 4. 2016, at 11:48, Alessio Stalla <> wrote:

> Your requirement is logically inconsistent. If there is only one possible instance of
Foo, there cannot be /another/ instance of Foo which is also a Bar.
> On 1 April 2016 at 04:28, OC <> wrote:
> Hello there,
> how do you make a hierarchy of classes, each of which happens to be a singleton?
> The naïve solution simply does not work:
> ===
> 85 /tmp> <qq.groovy
> @Singleton class Foo { }
> @Singleton class Bar extends Foo { }
> println "Foo: ${Foo.instance}, Bar: ${Bar.instance}"
> 86 /tmp> groovy qq
> Caught: java.lang.IllegalAccessError: tried to access method Foo.<init>()V from
class Bar
> java.lang.IllegalAccessError: tried to access method Foo.<init>()V from class Bar
>         at Bar.<init>(qq.groovy)
>         at Bar.<clinit>(qq.groovy)
>         at
> 87 /tmp>
> ===
> What is the proper way to achieve this?
> Thanks a lot,
> OC

View raw message