How does the 'protected constructor' pattern enforce a specific object-creation approach, like the Factory pattern?
Short answer
Making a class's constructor protected prevents external code from calling 'new' on it directly, while still allowing subclasses (or static factory methods within the class itself) to construct instances — commonly used to force construction through a validated static factory…
Advertisement
AModel answer
Making a class's constructor protected prevents external code from calling 'new' on it directly, while still allowing subclasses (or static factory methods within the class itself) to construct instances — commonly used to force construction through a validated static factory method.
class User {
protected constructor(public readonly email: string) {}
static create(email: string): User {
if (!email.includes('@')) throw new Error('Invalid email');
return new User(email);
}
}
// new User('x'); // Error: constructor is protected
User.create('sam@example.com'); // OKReal-world example
Guaranteeing every User instance is validated at creation time by forcing all construction through User.create().
Likely follow-ups
- How does this compare to using a private constructor instead of protected?
Related topics