Should an object write itself out to a file, or should another object act on it to perform I/O?

后端 未结 7 1684
予麋鹿
予麋鹿 2020-12-23 02:06

NOTE: Sorry for the long question!

I\'m trying to understand some key areas behind object orientation and I couldn\'t decide one way or another about my par

相关标签:
7条回答
  • 2020-12-23 02:48

    I think the correct approach is the Case 1, but your class may be defined this way to take advantage of both approaches:

    class Bob {
    
        IWriter _myWriter = null;
    
        public Bob(){
            // This instance could be injected or you may use a factory
            // Note the initialization logic is here and not in Save method
            _myWriter = new Writer("c://bob.xml")
        }
    
        //...
        public void Save(){
    
            _myWriter.Write(this);    
    
        }
        // Or...
        public void Save(string where){
    
            _myWriter.Write(this, where);
    
        }
        //...
    }
    

    This could be easily modified to put the writing logic and initialization in a base class so Bob class is even cleaner and independent of the persistence.

    0 讨论(0)
提交回复
热议问题