简体   繁体   中英

Java class design and SAX parser

Disclaimer....I'm new to Java and OOP.

I have a superclass with four subclasses. For each subclass, I need to parse an XML file. About 40%-50% of the elements in each XML are identical to one another, with the other half different for each subclass.

My initial approach was to include the SAX parser handler code in the superclass and simply list all possible XML elements into it. But then I faced the issue of communicating the other 50%-60% of elements specific to the subclasses back down to the subclasses. Since the superclass does not know about each subclass (I think), I think I would violate OOP principles if I somehow force that data down to the subclasses.

So now I'm thinking I might need to set up four different SAX parsers, one in each subclass. The super class would still be used for common instance variables and other methods. But I would also have quadruplication of some SAX parser code.

Any advice on how to proceed and stay true to OOP principles?

For this level of complexity I would recommend an alternate approach to mapping the XML to your object layer. Check out JAXB - it provides a very robust framework for these kind of mappings and handles object inheritance automatically.

As I understand it, you have 4 SAXParser s (or are they DefaultHandlers ? whatever...) that share a parent.

The parent should be able to keep the state that is "shared" between the 4 children. In inheritance-terms, children can surely know what methods and properties their parents have. They are, in fact, a kind of their parent. They need to know what they inherited, which is why you must import A if you're defining B extends A . What violates OOP principles is when an object has a reference to its container in an aggregation relationship -- that's backwards.

So, define the common callback handler routines in the parent and override the handlers in the children that must handle extra tags. Just make sure you call super() , and consider making your common state protected .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM