views:

220

answers:

4

How do I restrict object creation not more than 3 in Java class?

Can you give me an idea of how I can to do it?

+4  A: 

Instanciate your class via a factory (see design patterns) and limit it to 3 instances using a simple counter.

arnaud
simple static counter and have factory method synchronized.
Gladwin Burboz
+2  A: 

You need Modified Singleton. See this - same http://stackoverflow.com/questions/2323814/oops-design-patterns

Padmarag
A: 

Factory pattern is the way to go. Or a static counter can be used. Need to careful about thread safety.

fastcodejava
+1  A: 

You can also have a look at ObjectPool of Apache Commons. The source code is freely available...

extraneon