我下午的大部分时间都在阅读开放/封闭原则,但我似乎无法完全理解它。这是我已经阅读过的一些参考文章,似乎我错过了一些东西。
假设我有一个基本的通用存储库,它公开了一些最通用的方法,可以满足存储库的任何需求。
存储库
public abstract class Repository<TModel> where TModel : class {
protected Repository() { }
public abstract IList<TModel> FilterBy(
Expression<Func<TModel, bool>> filterExpression);
public abstract IList<TModel> GetAll();
public abstract TModel GetById(int id);
public abstract Save(TModel instance);
}
然后,我希望专攻 ProductRepository。
产品资料库
public abstract class ProductRepository : Repository<Product> {
protected ProductRepository() : base() { }
}
让我们假设我从这里的基本存储库中获得了我需要的一切。如果是这样,那么我觉得我没有打破开放/封闭原则,因为我没有定义任何新成员或类似的东西。
但是,如果我需要一种特殊的存储库,比如说一个 AlertLevelConfigurationRepository,并且业务需求规定我一次只能拥有一个 AlertLevelConfiguration。因此,存储库需要始终获取当前配置。
警报级别配置存储库
public abstract class AlertLevelConfigurationRepository
: Repository<AlertLevelConfiguration> {
protected AlertLevelConfigurationRepository() : base() { }
public abstract AlertLevelConfiguration GetCurrent();
}
现在,我觉得我打破了开放/封闭原则,因为这个新方法,因为这个类是从它的祖先修改后的派生类型。它被修改为存储库的基本定义不提供此GetCurrent
方法。此外,我很确定我永远不会使用任何基本方法,除非该Save
方法例外,因为更改级别配置可以是可配置的!
最后,我想知道我是否理解开放/封闭原则,不知何故我怀疑我理解。
我想知道这是否是一个违反原则的例子,如果不是,那么我想对原则本身进行一些解释。