Re: Java generics limitations?
- From: Thomas Hawtin <usenet@xxxxxxxxxxxxxxxxx>
- Date: Mon, 16 Jan 2006 18:11:12 +0000
seanwinship@xxxxxxxxx wrote:
I'm trying to use Java's generics to implement a concept that is straightforward with C++'s templates. The underlying idea is known as the Curiously Recurring Template Idiom, first described, as far as I know, by James Coplien. I've used it in C++ to encapsulate generic behavior like the Singleton pattern:
template <class T> class Singleton { private: static T instance_;
public: static T& instance() { return instance_; } };
Using this template, creating a Singleton is simple:
class Foo : public Singleton<Foo> { . . . };
Why not:
public final class Foo {
private static final Foo instance = new Foo();
public static Foo getInstance() {
return instance;
}
private Foo() {
;
}
...
}Doesn't seem too difficult. If you don't like all the typing and don't need a particular base class implementation:
public enum Foo {
INSTANCE;
...
}Other than enums, I hope you don't have too many singletons.
I'm coming to the conclusion that generics in Java are basically worthless except as a means of eliminating the need to do some casting when using collections. Are they really so limited or am I missing something?
You have to remember that Java is not C++. Generics are not templates. Just because some random hack works in C++ doesn't mean it should in Java. Bashing your head against the wall will just produce poor code.
Java generics are designed to express in the language certain constraints on types objects interact with. A static equivalent of polymorphism. That they do that superbly. IMHO, for the job they are designed to do they wipe the floor with C++ templates.
Tom Hawtin -- Unemployed English Java programmer http://jroller.com/page/tackline/ .
- Follow-Ups:
- Re: Java generics limitations?
- From: seanwinship
- Re: Java generics limitations?
- From: Chris Uppal
- Re: Java generics limitations?
- References:
- Java generics limitations?
- From: seanwinship
- Java generics limitations?
- Prev by Date: Re: EXCEPTION_ACCESS_VIOLATION
- Next by Date: Re: Override an inner class?
- Previous by thread: Re: Java generics limitations?
- Next by thread: Re: Java generics limitations?
- Index(es):
Relevant Pages
|