Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We can restrict the creation of Object for a particular class by little modification in Singleton design pattern as below:

public class LimitClass {

    private static LimitClass limInstance;
    public static int objCount = 0;

    private LimitClass(){
        objCount++;
    }

    public static synchronized LimitClass getLimInstance(){
        if(objCount < 3 ){
            limInstance = new LimitClass();
        }
        return limInstance;
    }
}

public class LimitObjectCreationTest {

    public static void main(String[] args) {

        LimitClass obj1 = LimitClass.getLimInstance();
        LimitClass obj2 = LimitClass.getLimInstance();
        LimitClass obj3 = LimitClass.getLimInstance();
        LimitClass obj4 = LimitClass.getLimInstance();
        LimitClass obj5 = LimitClass.getLimInstance();
        LimitClass obj6 = LimitClass.getLimInstance();

        System.out.println(obj1);
        System.out.println(obj2);

        System.out.println(obj3);
        System.out.println(obj4);
        System.out.println(obj5);
        System.out.println(obj6);
      }
}

Output of above code is like:

com.pack2.LimitClass@19821f
com.pack2.LimitClass@addbf1
com.pack2.LimitClass@42e816
com.pack2.LimitClass@42e816
com.pack2.LimitClass@42e816
com.pack2.LimitClass@42e816

After creation of three different object it is repeating the same 3rd object again and again. It is not creating the different object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...