Java Reference
In-Depth Information
continued
easily change our DAOs to an in‐memory data store instead of persisting the data
in a database, we could leave the clients to try the demo version for as long as they
wanted. (Without a persistent data store, the application would make no sense at
all!) Because we already had the DAO factory, we only needed to implement the in‐
memory DAO classes and tweak the factory code to return them when our database
was not present.
The result was so successful that I implemented another factory to control print
jobs to print to a nonformatted text i le instead of the real printer for the demo
version. These changes that took advantage of the factory pattern meant that we
could easily leave clients to evaluate our application for as long as they wanted and,
because the clients could not print formatted copies and persist i nancial data, the
application was useless in production.
Designing the system using factories was not a huge win at i rst but was a life saver
in the end. Design patterns tend to address future problems if they are used in the
right context.
Implementing the Factory Method in Plain Code
The factory method does not have boilerplate code for its implementation. Listings 6‐1 to 6‐6 show
implementations of the factory pattern using a DrinksMachine that dispenses different types of
drinks depending on the implementation of its subclasses.
LISTING 6‐1: DrinksMachine abstract class extended by concrete implementations
public abstract class DrinksMachine {
public abstract Drink dispenseDrink();
public String displayMessage(){
return "Thank for your custom.";
}
}
LISTING 6‐2: CoffeeMachine implementation of the DrinksMachine abstract class
public class CoffeeMachine extends DrinksMachine {
public Drink dispenseDrink() {
return new Coffee();
}
}
 
Search WWH ::




Custom Search