I have some code:
/// <summary>
/// Represents Record Locator class
/// </summary>
public class RecordLocator : IRecordLocator
{
/// <summary>
/// The Record Locator string, for example: ZT8C4O
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="RecordLocator"/> class.
/// </summary>
/// <param name="recordLocator">The record locator string.</param>
private RecordLocator(string recordLocator)
{
Name = recordLocator;
}
/// <summary>
/// Parses the specified record locator.
/// </summary>
/// <param name="recordLocator">The record locator string.</param>
/// <returns></returns>
public static IRecordLocator Parse(string recordLocator)
{
if (string.IsNullOrEmpty(recordLocator))
throw new ArgumentNullException("recordLocator");
if (recordLocator.Length != 6)
throw new ArgumentException("recordLocator.Length != 6");
return new RecordLocator(recordLocator);
}
}
/// <summary>
/// Represents Record Locator interface
/// </summary>
public interface IRecordLocator : IHideObjectMembers
{
/// <summary>
/// The Record Locator string, for example: ZT8C4O
/// </summary>
string Name { get; }
}
-
What is this design-pattern called? When you have a class, which instantiating itself (and probably have a private constructor)?
Another example of this isSystem.DateTime
class of .NET framework. -
Is it OK to do it like that?
2
It is a static factory pattern. In this particular instance it doesn’t currently provide anything that a traditional constructor couldn’t(IE object pooling or multiple implementation types) so it doesn’t add much value, but isn’t wrong.
1
Besides “static factory” (see Sign’s answer), I have also heard the term “creation method”. Creation methods have the advantage that they have a specific name that conveys meaning. You can also create several methods with the same parameter signature, e.g. an Angle
struct with methods static Angle FromDegrees(double degrees)
and FromRadians(double radians)
. This is not possible with constructors.
I can’t recognize any established design patterns here. However, parsing a string to build an object is good, I have seen many examples in Java(my primary language) like Integer.parseInt
.
You cannot have a constructor for parsing strings because if the parsing fails, you must throw an exception(expensive) or keep an object in undefined state(bad). Parsing method can either generate a new object or return null.
2
No such pattern exists in GoF book. Nor I heard about this kind of pattern.
Yes it is OK to do that. But be careful, because it limits extensibility.
1