开发者

Is this the Open/Closed principle? And if not

开发者 https://www.devze.com 2023-03-08 04:38 出处:网络
Considering the following code public interface IEntity { int Id { get; set; } } public class User : IEntity {

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 IsVali开发者_Go百科d(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.


As you can read on wikipedia, the OCP has a couple of definitions. The one that's probably mostly used on stackoverflow is the polymorphic one. I prefer the protected variations spin, since ideally we want to have a design that allows for variations in one place, which don't affect certain (protected) classes that depend on those variations.

In your example, the variations in the implementations of IEntity would not affect the client classes that use IEntities, provided you don't have direct coupling between the clients and the implementations. That is, clients should only know about IEntities and not about specific implementations. This often requires implementing a factory so that clients can access implementations without knowing them concretely.

0

精彩评论

暂无评论...
验证码 换一张
取 消