2011-11-10 2 views
2

다른 말로하면, 클래스는 하위 클래스를 인스턴스화했거나 인스턴스가 직접 생성 되었기 때문에 생성자가 호출되었는지 여부를 어떻게 추적 할 수 있습니까?클래스의 DIRECT 인스턴스 수를 제한하십시오.

[cosider하십시오 다음 샘플 코드] :

내가 new Parent(...)를 호출 카운트에서 제외하여 만든 Parent 클래스의 직접적인 인스턴스의 수를 제한 할
class Parent 
{ 
    ............. 
    ......... 
    .............. 
} 

class Child1 extends Parent 
{ 
    ............. 
    ......... 
    .............. 
} 

class Child2 extends Parent 
{ 
    ............. 
    ......... 
    .............. 
} 

, Parent 인스턴스의 수에 의한 생성 어린이 수업 중 하나를 가르치십시오 Child1 또는 Child2. 이 작업을 수행 할 이유

+0

무엇에 "자식 클래스"를? 내면의 수업을 의미합니까? 이 경우에 대한 몇 가지 샘플 코드를 제공 할 수 있습니까? –

+0

@DmitryBeransky, 내 질문을 편집했습니다. 왜 왜 downvote가 있었습니까? –

답변

4

당신은

static final AtomicInteger count = new AtomicInteger(); 

// in your Parent constructor. 
if (getClass() == Parent.class && count.incrementAndGet() >= LIMIT) 
    throw new IllegalStateException(); 

당신이 설명 할 수 할 수 있습니까? 한도에 도달하면 어떻게되고 싶습니까?

+0

고마워요,이 작품은 물론, 제한에 도달하면 다른 클래스에 도달했을 때 던져 질 내 자신의 예외가있다. –

2

단일 책임 원칙은이 인스턴스 제한 로직을 아마도 공장 클래스로 분리 할 것을 제안합니다. 이것은 생성자로부터 예외를 던지지 않는 이점이 있습니다.

0

내가 이런 짓을 했을까 :

public class Parent { 

    public Parent() { 
     if (count.incrementAndGet() >= LIMIT) { //count is an AtomicInt/Long 
      throw new InstantiationException("Too many instances"); 
     } 

    protected Parent(boolean placeholder) { //protected means only subclasses can call it 
     //do nothing with the placeholder, but it differentiates the two constructors 
    } 

} 
관련 문제