2016-09-23 3 views
4

모든 인스턴스를 원본으로 이동시키는 정적 메서드를 만들려고하지만 인스턴스 변수 (예 : xPosition 및 yPosition)에서 정적 메서드를 사용할 수 없습니다.Java에서 모든 인스턴스를 수행하는 방법

모든 인스턴스를 반복해야합니까, 아니면 정적 방법으로이 작업을 수행 할 수 있습니까?

미리 감사드립니다.

+0

인스턴스의 "출처"란 무엇입니까? 예를 들어 보셨습니까? – AxelH

+0

질문 : 주어진 클래스의 모든 인스턴스를 검색하는 방법이 있습니까? 컬렉션에 사용 된 모든 인스턴스를 수동으로 저장하지 않은 경우 대답은 no입니다. –

+0

캔버스에 페인팅하고 (0,0)을 원점으로 사용합니다. –

답변

4

당신의 모든 인스턴스가 있는지 확인하기 위해 등 스레드로부터의 안전성과 관련하여 더 많은주의를 필요로하여 그런 다음

public class MyClass { 
    /** 
    * Thread-safe collection used to store all existing instances 
    */ 
    private static final Collection<MyClass> INSTANCES = new ConcurrentLinkedQueue<>(); 

    private MyClass() {} 

    public static MyClass newInstance() { 
     // Create the instance 
     MyClass instance = new MyClass(); 
     // Publish the instance 
     INSTANCES.add(instance); 
     return instance; 
    } 

    public static void release(MyClass instance) { 
     //Un-publish my instance 
     INSTANCES.remove(instance); 
    } 

    public static void releaseAll(Predicate<MyClass> predicate) { 
     //Un-publish all instances that match with the predicate 
     INSTANCES.stream().filter(predicate).forEach(INSTANCES::remove); 
    } 

    public static void apply(Consumer<MyClass> consumer) { 
     // Execute some code for each instance 
     INSTANCES.stream().forEach(consumer); 
    } 
} 

코드 : 클래스, 나는 생성자 private을하고, 같은 것을 만들고에게 인스턴스를 게시 static 메소드를 호출 적용하여 직접 인스턴스를 생성 할 수 있습니다 방지 할 수

// Create my instance 
MyClass myClass = MyClass.newInstance(); 
// Execute some code here 
... 
// Release the instance once the work is over to prevent a memory leak 
MyClass.release(myClass); 
... 
// Execute some code on all instances 
// Here it will print all instances 
MyClass.apply(System.out::println); 
... 
// Release all instances that match with a given test 
MyClass.releaseAll(myClass -> <Some Test Here>); 
+0

가장 유용한 통찰력! 감사!! –

3

모든 인스턴스의 정적 레지스트리가있는 경우 정적 방법으로 수행 할 수 있습니다.

class YourClass { 
    static List<YourClass> instances = new ArrayList<>(); 

    YourClass() { 
    instances.add(this); // Yuk! Unsafe publication. 
    } 

    static void moveAll() { 
    for (YourClass instance : instances) { 
     // Do something to instance. 
    } 
    } 
} 

하지만 난 당신이 그렇게하지 않는 것이 좋습니다,하지만 대신 비 정적 레지스트리 클래스 거라고 :

class YourClassRegistry { 
    List<YourClass> instances = new ArrayList<>(); 

    void add(YourClass instance) { 
    instances.add(instance); 
    } 

    void moveAll() { 
    for (YourClass instance : instances) { 
     // Do something to instance. 
    } 
    } 
} 

예 사용은 :

YourClassRegistry registry = new YourClassRegistry(); 
registry.add(new YourClass()); 
registry.add(new YourClass()); 
registry.add(new YourClass()); 

registry.moveAll(); 

이 당신을 허용을 별도로 이동할 수있는 별도의 "인스턴스"그룹이 있어야합니다.

(레지스트리의 정적 버전 등) 글로벌 변경할 상태는 목에 통증 테스트 가능성을 감소

+0

콧노래는 정말 스레드 안전하지 않음 –

+1

스레드를 안전하게 만들 수 있습니다. TBH, 그건 여기서 두 번째 관심사입니다. –

+0

은 오류가 발생하기 쉽지 않으므로 YourClass의 인스턴스를 만들지 않아야합니다. 그렇지 않으면 추가 호출을 놓칠 수 있습니다. 현재 YourClassRegistry는 YourClass의 Collection 일뿐입니다. 더 이상 진행해야합니다. 동의하지 않습니까? –

관련 문제