the customer. By designing to interfaces, we can swap out an implementation of an interface for a mock
implementation, which allows us more flexibility when testing. For example, when unit testing a web
controller, we definitely want to focus on whether the controller is behaving correctly, assuming that the
service classes it depends on are working properly. In this case, it will be very useful to provide a "mocked"
version of the service class that always return the expected results to the web controller under test.
The Factory Pattern
One of the key problems you will encounter when implementing an application where all the
components are defined in terms of interfaces is how your application goes about locating instances of
classes that implement the interfaces. A traditional solution to this is to use the Factory Pattern. The
Factory Pattern defines a class whose responsibility is to provide application components with
implementations of other application components; in this case, the available components are defined in
terms of interfaces, not concrete implementations. Consider a system that has a business interface
called OrderService. Other components in the system want to obtain implementations of this interface
without knowing ahead of time which implementation they need. To implement such a system, we can
build a Factory class like the one shown in Listing 12-1. Note that the OrderService interface and the
DefaultOrderServiceImpl implementation class (which implements the OrderService interface) are
empty, without any methods defined.
Listing 12-1. A Basic Factory Class Implementation
package com.apress.prospring3.ch12.factory;
import com.apress.prospring3.ch12.service.OrderService;
import com.apress.prospring3.ch12.service.impl.DefaultOrderServiceImpl;
public class BasicFactory {
private static final BasicFactory instance;
private OrderService orderService;
static {
instance = new BasicFactory();
}
public static BasicFactory getlnstance() {
return instance;
}
public BasicFactory() {
this.orderService = new DefaultOrderServiceImpl();
}
public OrderService getOrderService() {
return this.orderService;
}
}
This is a simplistic Factory implementation, but it does illustrate the basic Factory Pattern
approach. Now any application that wants to get access to an implementation of OrderService simply
uses the getOrderService() method of the BasicFactory class.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home