I have multiple classes that are not allowed to modify each other’s fields, but instead must request to modify by adding a request object to the Main class’s queue. The Main class, at the end of each loop, will perform the requested modifications.
public class Main {
public static ClassA a = new ClassA();
public static ClassB b = new ClassB();
private static List<Request> requestQueue = new ArrayList<Request>(); // List holds all requests
public static void main(String args[]) {
while (true) {
a.tick();
b.tick();
for (Request r : requestQueue) {
r.field = r.value; // All requests are fulfilled
}
requestQueue.clear();
}
}
public static <ValueType> void addModificationRequest(ValueType field,
ValueType value) {
requestQueue.add(new Request<ValueType>(field, value));
}
}
// Request Object
public class Request<ValueType> {
ValueType field;
ValueType value;
public Request(ValueType field, ValueType value) {
this.field = field;
this.value = value;
}
}
// Classes
public class ClassA {
String name = "A";
public void tick() {
Main.addModificationRequest(Main.b.name, "NewNameB"); // Try to change b name
}
}
public class ClassB {
String name = "B";
public void tick() {
// Nothing
}
}
I know the code is messy, but its the simplest way I have thought of so far. Does anyone know any good design patterns that can accomplish this in a simpler and more robust way?
(Note: I must have it this way, there is no possibility of allowing the classes to directly modify each other.)
Edit: The classes will have more than one modifiable variable. I also need to determine if any requests try to modify the same variable, so I can ignore one or both.
Edit: Thanks for all the help, I really appreciate it! I have decided to let the classes keep track of their own modifications. I am also going to use the same Request object I have been using because it is simple and straightforward. Again, thank you.
Maybe this doesn’t apply for your use case, but you could have the objects themself keep track of pending modifications, and then have a call, made from your main class, that modifies the actual fields themself.
If you only need the set operation, keeping track of modifications is as easy as keeping an extra field for each field in the class. If you need a series of, say, arithmetic operations, you can use a list of modifications.
Your main class must keep track of all objects supporting delayed modification and call performSet on them each tick. Make them implement an interface and keep them in a list.