Consider this:
public MyClass
{
private Resource _myResource;
public Resource MyResource
{
get
{
if(_myResource == null)
{
_myResource = new Resource();
}
return _myResource;
}
}
public void UseResource()
{
MyResource.DoSomething();
}
}
Is this a recognised pattern, or possibly an anti-pattern? I've never seen it suggested in any books, but it does come up time and time again in code I see. I think the logic of this is that _myResource is instantiated 'just in time'. To me, it seems a bit smelly. UserResource() is accessing a public property from within the class, and the resource can never really be accessed through the private member - if someone did, _myResource could be null.
Maybe performance reasons may sometimes necessitate, but I would generally favour instantiating in the constructor, or just having an instance of Resource local to the method.
So is this an accepted pattern, or should it be avoided?
