Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make all instances in Java do something [closed]

I am trying to create a static method that moves all instances to the origin, but I can't use a static method on instance variables (like xPosition and yPosition).

Would I have to loop through all of the instances, or is there a way to do this with a static method?

Thanks in advance!

like image 306
Jeff Ciaccio Avatar asked Mar 11 '23 01:03

Jeff Ciaccio


1 Answers

To ensure that you have all the instances of your class, I would prevent allowing to create the instances directly by making the constructors private and enforcing calling a static method to create and publish the 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>);
like image 122
Nicolas Filotto Avatar answered Mar 19 '23 17:03

Nicolas Filotto