How to make all instances in Java something

I am trying to create a static method that moves all instances to the beginning, but I cannot use a static method for instance variables (e.g. xPosition and yPosition).

Do I need to iterate over all instances or is there a way to do this with a static method?

Thanks in advance!

+4
source share
2 answers

To make sure that you have all the instances of your class, I would not allow you to instantiate directly by creating constructors privateand using a method call staticto create and publish an instance, something like:

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);
    }
}

Then your code will be:

// 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>);
+4
source

, .

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();

"", .

(, ) - , , ..

+3

Source: https://habr.com/ru/post/1655612/


All Articles