Jon Cardoso-Silva
Jon Cardoso-Silva

Reputation: 990

Best pattern to update an object each iteration of an algorithm

I have an algorithm that alters the state of an object each generation, depending on some semi-random modifications made to a list. I made a simplification to be clearer, so assume I have two class:

public class Archive{

...

}

public class Operation{

...

}

In another class,Algorithm, a method iterates, make some adjustments to a List<Operation> (similar to Genetic Algorithm crossovers and mutations). This list among with other objects related are used to update an Archiveobject, making a lot of calculations and modifications to the Archive object.

In the current version of my code I have a ArchiveUpdateclass that has a internal Archive object and a method that receives ALL the objects used in the update to change the Archive. I think this way is kinda fuzzy and I can't think of another way of doing this better, can anybody help?

Upvotes: 1

Views: 499

Answers (2)

user1697575
user1697575

Reputation: 2848

Its hard to grasp completely...but from what I understood you need a pattern that would allow you to be notified if a "monitored" state changed. If that is the case you should look at Observer pattern it provides a simple way of monitoring state changes.

Upvotes: 1

Thorn G
Thorn G

Reputation: 12766

Have you considered making the Archive immutable and providing methods that return new Archive instances based on an existing archive? That is, something like:

public class Archive {
  private final String field;
  public Archive(String field) { this.field = field; }

  public Archive changeField(String newField) { return new Archive(newField); }
}

If your objects are all immutable, it's much easier to reason about their state and you wouldn't need an ArchiveUpdate class. However, without more examples of exactly how these classes get used I can't suggest much else.

Upvotes: 1

Related Questions