|
Designing with Constructors and Factories
An Introduction with Examples in Java |
|
Prof. David Bernstein
|
| Computer Science Department |
| bernstdh@jmu.edu |
new operator calls the constructor)
SecurityQuotation
StockQuotation
FutureQuotation
String
representation (e.g., lines read from a file)
The constructor in SecurityQuotation is straightforward.
The constructor in StockQuotation is elegant.
The constructor in FutureQuotation is awful!
It has to do unnecessary work and it has to know what work was done in the base class.
fromString() method that sets
the attributes of an empty object from a String
representation
The SecurityQuotation class now needs a default constructor
(because the derived classes will), but it can be protected.
The code that was in the constructor can now be moved to the
fromString() method (which can also be protected), and
this method can return the StringTokenizer it used in case
a derived class needs to use it.
The StockQuotation class now needs a public default constructor
(because someone that wants to create a StockQuotation from
a String will first need to construct an empty object
and then call its fromString()).
The fromString() method is now elegant because it can use
the same StringTokenizer that the
fromString() method in the SecurityQuotation
class used.
The FutureQuotation class also needs a public default
constructor.
The fromString() method is now elegant because it can use
the same StringTokenizer that the
fromString() method in the SecurityQuotation
class used.
fromString() methods are both elegant
String
first has to use the default constructor and then call
the fromString() method
The default constructor in the StockQuotation class
is now protected.
The fromString() method remains the same (though it
could be made protected if desired) and a static factory
method is added.
The default constructor in the FutureQuotation class
is now protected.
The fromString() method remains the same (though it
could be made protected if desired) and a static factory
method is added.