I want to have only 5 instance of a class throughout the application life time. How can I achieve this? Please give sample code, if possible.
create static field howMany which will be incremented each time when the contructor is called.
When howMany => 5 - dany to create an object.
class Sample
{
private static int i = 0;
private Sample()
{
}
public static Sample CreateInstance()
{
if(i <5)
{
i++;
return new Sample();
}
else
throw new Exception("Can not create more then 5 instance of this class");
}
}
The Factory pattern could be your friend. One (fictional, not threadsafe and thus quite simple) example to illustrate the approach:
public static MartiniFactory {
private static int olives = 100; // you asked for '5' but 100 is more realistic
// for this example.
public static Drink createMartini() throws OutOfOlivesException {
if (olives > 0) {
olives--;
return new Martini(new Gin(4), new Vermouth(1), new Olive());
else {
throw new OutOfOlivesException();
}
}
// forgot to mention, only the factory (=bar) is able to create Martinis, so:
private class Martini {
Martini(Ingredient... ingredients) {
// ...
}
// ....
}
}
EDIT
The license example was not too good - so I moved it to a domain that expects, that objects created by the factory are not returned and destroyed without noticing the factory. The Bar can't create Martinis when there is no olive left and it definitly doesn't want the drink back after it has been consumed ;-)
EDIT 2 And for sure, only the factory can create Instances (=Drinks). (No guarantee, that the added inner private class fulfills this requirement, don't have an IDE at hand to do a quick test .. feel free to comment or edit)
public class FiveInstance {
private static int instanceCount = 0;
private FiveInstance(){
}
public static FiveInstance getNewInstance() throws InstanceExceededException{
if(instanceCount < 5){
instanceCount++;
return new FiveInstance();
}else{
throw new InstanceExceededException();
}
}
}
Create a private static
member to count the instances of the class
. Then, make sure every constructor of your class increment this static
variable and test for overflow. If you have more than one constructor I suggest that you make one constructor implement this behaviour and the others should call it. The behavior of the constructor upon an attempt to create a sixth instance is up to you. Maybe you want to throw an Exception
.
As Singletons shall be made with enums (See "Effective Java"):
public enum FiveInstance {
INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5;
public void anyMethod() {}
}
Greetz GHad
You can try following code but written in C#, you can get a basic idea how can it be done.
public class MultiTone
{
private static MultiTone _cache;
private static int _counter=5;
MultiTone()
{
}
public static MultiTone GetInstance()
{
if(_counter==0)
{
return _cache ?? (_cache = new MultiTone());
}
_counter--;
return new MultiTone();
}
}
And mind that this class is't intended to use in multi-threading environment.
I think you can't. You can force that if somebody want to create or destroy an instance has to use these static methods:
import java.util.*;
public class Fiveton {
public final static int MAX_INSTANCES = 5;
private static List<Fiveton> instances = new ArrayList<Fiveton>();
private Fiveton() { }
public static Fiveton getInstance() {
if (instances.size()>=MAX_INSTANCES) throw new RuntimeException("Hey! You've reached the maximum of instances: " + MAX_INSTANCES);
Fiveton instance = new Fiveton();
instances.add(instance);
return instance;
}
public static void destroy(Fiveton instance) {
instances.remove(instance);
}
}
The problem is method destroy. You can't be sure that someone is still referencing the destroyed object.
Look at Object pool pattern. Its java implementation is greatly described in Grand Patterns in Java V1.
Short description from the book overview:
Object Pool
Manage the reuse of objects for a type of object that is expensive to create or only a limited number of a kind of object can be created.