I’m thinking about creating some classes along a “single-use” design pattern, defined by the following features:
- Instances are used for performing some task.
- An instance will execute the task only once. Trying to call the
executemethod twice will raise an exception. - Properties can be modified before the
executemethod is called. Calling them afterward will also raise an exception.
A minimalist implementation might look like:
public class Worker
{
private bool _executed = false;
private object _someProperty;
public object SomeProperty
{
get { return _someProperty; }
set
{
ThrowIfExecuted();
_someProperty = value;
}
}
public void Execute()
{
ThrowIfExecuted();
_executed = true;
// do work. . .
}
private void CheckNotExcecuted()
{
if(_executed) throw new InvalidOperationException();
}
}
Questions:
- Is there a name for this?
- Pattern or anti-pattern?
This looks like a form of a balking pattern.
If it appears logical for your specific object to behave in this way, I don’t see a problem with it.