Java-Web:Using a factory for creating XML or JSON

From Juneday education
Jump to: navigation, search

Work in progress

This chapter is work in progress. Remove this section when page is production-ready.

Introduction

This chapter is about dynamically choosing implementation for creating either XML or JSON. The lecture shows an example with a Java program where the user chooses what format the program should output, by giving and argument to the program.

The Java application, uses a factory to, based on the user's argument, get a formatter for some data. The factory will return a Formatter for the right type of output (XML or JSON).

The video lecture (split into six videos) on how you can write an application with a factory class with a factory method for getting an instance of interface type based on a user-provided string argument. The interface defines a formatter class for formatting a list of Java objects to some data format (like XML or JSON). All implementing classes are loaded dynamically using a properties file with format name and implementing formatter class.

The point of the lecture and example is to show you a way to create Java applications which doesn't "know" about what classes to use by means of hard coded class names. Instead, the properties file (and XML file) keeps a list of keys and class names. When the factory class is first loaded, it reads the properties files and loads each class.

Each class, in turn, when loaded, registers an instance of itself with the factory together with a key.

This allows for a user to provide a format argument, say "xml" to the application. The main method fowards this argument to the factory. The factory looks up the key and returns a reference to the corresponding object of the implementing class for XML.

Slides and videos

Slides

Videos

Links

Further reading

TODO: some more links

Source code

Navigation

Up next: Exercises!

« PreviousBook TOCNext »