I've seen this pattern in Enumerator. It makes sure the collection haven't been altered while enumerating over the items.
public class Versioned
{
internal int version = 0;
public void ThisBreaksVersion()
{
version++;
}
}
public class WorksOnVersioned
{
private readonly int version;
private readonly Versioned versioned;
public WorksOnVersioned(Versioned versioned)
{
this.versioned = versioned;
this.version = versioned.version;
}
public void DoWork()
{
if( version != other.version )
throw new Exception(); // Ooop.. Out of sync!
}
}
var v1 = new Versioned();
var w1 = WorksOnVersioned(v1);
w1.DoWork(); // Yup
var v2 = new Versioned();
var w2 = WorksOnVersioned(v2);
v2.ThisBreaksVersion();
w2.DoWork(); // v2 has changed -> exception!
I can also see this is useful when using a shared resource to make sure the local copy is the same as the one in the resource.
But what is this pattern called? Is there something else it can be useful for?