views:

100

answers:

1

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?

+3  A: 

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.)

Jon Skeet
Since no one else has answered, this pattern is now called "version snapshotting" :)
simendsjo