readonly class design when a non-readonly class is already in place

前端 未结 5 2518
借酒劲吻你
借酒劲吻你 2021-02-19 16:55

I have a class that upon construction, loads it\'s info from a database. The info is all modifiable, and then the developer can call Save() on it to make it Save that informati

5条回答
  •  长情又很酷
    2021-02-19 17:33

    A quick option might be to create an IReadablePerson (etc) interface, which contains only get properties, and does not include Save(). Then you can have your existing class implement that interface, and where you need Read-only access, have the consuming code reference the class through that interface.

    In keeping with the pattern, you probably want to have a IReadWritePerson interface, as well, which would contain the setters and Save().

    Edit On further thought, IWriteablePerson should probably be IReadWritePerson, since it wouldn't make much sense to have a write-only class.

    Example:

    public interface IReadablePerson
    {
        string Name { get; }
    }
    
    public interface IReadWritePerson : IReadablePerson
    {
        new string Name { get; set; }
        void Save();
    }
    
    public class Person : IReadWritePerson
    {
        public string Name { get; set; }
        public void Save() {}
    }
    

提交回复
热议问题