Example:





import java.util.*;

public class SingletonDesignPattern {

    public final static int MAX_INSTANCES = 5;

    private static List<SingletonDesignPattern> instances = new ArrayList<SingletonDesignPattern>();


    private SingletonDesignPattern() {
   
    }
    static{
       
        System.out.println("execueted once");
    }


    public static SingletonDesignPattern getInstance() {
        if (instances.size()>=MAX_INSTANCES) throw new RuntimeException("Hey! already: " + MAX_INSTANCES+" Instances are created...Don't try to create 6th Object");
        SingletonDesignPattern instance = new SingletonDesignPattern();
        instances.add(instance);
        return instance;
    }


}


If you trying to create a 6th object ,exeception raised (like user defined )

1 comments:

  1. ya that's working,but i want another way to restrict the objects

    ReplyDelete