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

后端 未结 7 1682
予麋鹿
予麋鹿 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:35

    Do this:

    public interface Writable {
        public void Save(Writer w);
    }
    
    public interface Writer {
        public void WriteTag(String tag, String cdata);
    }
    
    public class Bob : Writable {
        private String ssn = "123-23-1234";
        public void Save(Writer w) {
            w.WriteTag("ssn", ssn);
        }
    }
    
    public class XmlWriter : Writer {
        public XmlWriter(Sting filename) {...}
        public void WriteTag(String tag, Sting cdata) {...}
    }
    

    Obviously this isn't a complete solution but you should get the general idea.

提交回复
热议问题