Guest User

Untitled

a guest
Aug 14th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. Limit the number of DIRECT Instances of a class
  2. class Parent
  3. {
  4. .............
  5. .........
  6. ..............
  7. }
  8.  
  9. class Child1 extends Parent
  10. {
  11. .............
  12. .........
  13. ..............
  14. }
  15.  
  16. class Child2 extends Parent
  17. {
  18. .............
  19. .........
  20. ..............
  21. }
  22.  
  23. static final AtomicInteger count = new AtomicInteger();
  24.  
  25. // in your Parent constructor.
  26. if (getClass() == Parent.class && count.incrementAndGet() >= LIMIT)
  27. throw new IllegalStateException();
  28.  
  29. public class Parent {
  30.  
  31. public Parent() {
  32. if (count.incrementAndGet() >= LIMIT) { //count is an AtomicInt/Long
  33. throw new InstantiationException("Too many instances");
  34. }
  35.  
  36. protected Parent(boolean placeholder) { //protected means only subclasses can call it
  37. //do nothing with the placeholder, but it differentiates the two constructors
  38. }
  39.  
  40. }
Add Comment
Please, Sign In to add comment