Considering the following code
public interface IEntity {
int Id { get; set; }
}
public class User : IEntity {
public int Id { get; set; }
}
public abstract class RepositoryBase<TEntity> where TEntity : IEntity {
public bool Save(TEntity entity) {
if (!IsValid(entity)) return false;
// Write to data store
return true;
}
public abstract TEntity CreateNew();
protected abstract bool IsValid(TEntity entity);
}
public class UserRepository : RepositoryBase<User> {
public override User CreateNew() {
return new User {
Id = 3
};
}
protected override IsValid(User entity) {
return entity.Id > 0;
}
}
Is this the open/closed principle? i.e deferring most of the responsibility to the base class and allowing certain functional responsibilities to inheriting classes.
It doesn't feel like it is, so if it not the open/closed principle then what kind of design pattern is this?
Cheers
You can create new repositories for different data structures by extending RepositoryBase<TEntity>
in different ways, without having to modify the code in RepositoryBase<TEntity>
. That is the core meaning of the open/closed principle.
That said, the open/closed principle is a general design principle and not a design pattern. The main design pattern visible in the relation of the Save
and IsValid
methods is Template Method.