What is this design pattern used in Enumerator.?

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?

Answers


I don't know of any named pattern for this - you might call it "version snapshotting" or something like that, where the important part is that you don't need to snapshot the whole of the mutable data if all you're interested in is knowing whether or not it's changed. (i.e. a snapshot simply becomes invalid, rather than remaining unchanged in the face of changes to the original.)


Need Your Help

How to change values in raster inside loop

r loops raster

I have aerial images of forests where I need to compute fragmentation index. I know how to do it for any individual image, but I want to use loop because the is a bunch of them.