0

I want to limit the number of instances of a class and I do not want to do that using a static count because of some of drawbacks of using static variable like thread saftey and others mentioned in following post: Why are static variables considered evil?.

Is their any way I can do this?

Community
  • 1
  • 1
ankush
  • 949
  • 2
  • 14
  • 33
  • 1
    Most of the draw-backs are inherent in global mutable state. `static` isn't the problem. i.e. limiting the number of instances globally is the "evil" thing, not static. – CodesInChaos Nov 03 '12 at 12:05
  • And how do you define the number of instances? When does it decrease? .net's finalization is not deterministic. – CodesInChaos Nov 03 '12 at 12:06
  • 1
    but why would you want to to this? What are you trying to accomplish? – Esben Skov Pedersen Nov 03 '12 at 12:08
  • i want to add a licensing in to my software where we have to limit the number of instances created of a class , that is the reason i am looking for a solution. – ankush Nov 04 '12 at 04:38

2 Answers2

5

The only way of doing that is to use a part of the factory pattern. You have than a class object, which creates objects of another class and on every 'new' call, you increase your counter which is a non static class variable in this case.

A.B.
  • 2,374
  • 3
  • 24
  • 40
  • What is the visibility of the constructor of the object you want to instantiate with this factory? `public`, `internal`, `protected`, `private`? How do you ensure the class in question is not created out of control of your factory class? – Guillaume Nov 03 '12 at 12:07
  • I actually not thought about it. But that depends what programming language you are using. For example when you are using C++, you can declare the 2 classes as friends (s. friend keyword in C++). Otherwise you can put those 2 classes in a seperate namespace. (it would be internal than if i'm not mistaken. correct me if it's wrong.) – A.B. Nov 03 '12 at 12:15
  • Or what if you create more than one factory? You could make it a singleton, but then you're back to statics. – hatchet - done with SOverflow Nov 03 '12 at 12:50
  • @hatchet you need a static counter only then if you need to count inside the corresponding class/object. Otherwise you can always extend your has-a relation according to your problem definition. regarding to your question: you can use a Facade. – A.B. Nov 03 '12 at 19:18
0

If you don't want to use a static field for counting your instances, you can define an instance field and use Interlocked.Decrement(out counter), this method atomically decrements your counter.

it is a thread-safe way to decrement an integer, so no race condition occurs between decrementing the count.

Ehsan Mirsaeedi
  • 6,924
  • 1
  • 41
  • 46