Showing posts with label Skripsi. Show all posts
Showing posts with label Skripsi. Show all posts

Thursday, February 7, 2013

Model View ViewModel (MVVM)

What is MVVM?
The Model View ViewModel (MVVM) is an architectural pattern used in software engineering that originated from Microsoft as a specialization of the presentation model design pattern introduced by Martin Fowler. Largely based on the model–view–controller pattern (MVC), MVVM is targeted at modern UI development platforms which support Event-driven programming, such as HTML5, Windows Presentation Foundation (WPF), Silverlight and the ZK framework.

MVVM facilitates a clear separation of the development of the graphical user interface (either as markup language or GUI code) from the development of the business logic or back end logic known as the model (also known as the data model to distinguish it from the view model). The view model of MVVM is a value converter meaning that the view model is responsible for exposing the data objects from the model in such a way that those objects are easily managed and consumed. In this respect, the view model is more model than view, and handles most if not all of the view’s display logic (though the demarcation between what functions are handled by which layer is a subject of ongoing discussion and exploration). The view model may also implement a mediator pattern organising access to the backend logic around the set of use cases supported by the view.

MVVM was designed to make use of data binding functions in WPF to better facilitate the separation of view layer development from the rest of the pattern by removing virtually all GUI code (“code-behind”) from the view layer. Instead of requiring user interface (UXi) developers to write GUI code, they can use the framework markup language (e.g. XAML) and create bindings to the view model, which is written and maintained by application developers. This separation of roles allows interactive designers to focus on UX needs rather than programming or business logic, allowing for the layers of an application to be developed in multiple work streams for higher productivity. Even when a single developer works on the entire code base a proper separation of the view from the model is more productive as the user interface typically changes frequently and late in the development cycle based on end-user feedback.

Elements of the MVVM pattern include:
Model: as in the classic MVC pattern, the model refers to either (a) a domain model which represents the real state content (an object-oriented approach), or (b) the data access layer that represents that content (a data-centric approach).
View: as in the classic MVC pattern, the view refers to all elements displayed by the GUI such as buttons, labels, and other controls.

View model: the view model is a “model of the view” meaning it is an abstraction of the view that also serves in mediating between the view and the model which is the target of the view data bindings. It could be seen as a specialized aspect of what would be a controller (in the MVC pattern) that acts as a converter that changes model information into view information and passes commands from the view into the model. The view model exposes public properties, commands, and abstractions. The view model has been likened to a conceptual state of the data as opposed to the real state of the data in the model. The term "View model" is a major cause of confusion in understanding the pattern when compared to the more widely implemented MVC or MVP patterns. The role of the controller or presenter of the other patterns has been substituted with the framework binder (e.g. XAML) and view model as mediator and/or converter of the model to the binder.

Controller: some references for MVVM also include a controller layer or illustrate that the view model is a specialized functional set in parallel with a controller, while others do not. This difference is an ongoing area of discussion regarding the standardization of the MVVM pattern.

Binder: the use of a declarative databinding and command bind technology is an implicit part of the pattern. Within the Microsoft stack this is the XAML technology. Essentially this architectural component frees the developer from being obliged to write boiler plate logic to synchronise the view model and view. It is the organisation of code to make best use of this capability which distinguishes the pattern from both MVC and MVP. When implemented outside of the Microsoft stack the presence of a declarative databinding technology is a key enabler of the pattern.

Why MVVM?
The Model-View-ViewModel (MVVM) pattern helps you to cleanly separate the business and presentation logic of your application from its user interface (UI). Maintaining a clean separation between application logic and UI helps to address numerous development and design issues and can make your application much easier to test, maintain, and evolve. It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of the application.
Using the MVVM pattern, the UI of the application and the underlying presentation and business logic is separated into three separate classes: the view, which encapsulates the UI and UI logic; the view model, which encapsulates presentation logic and state; and the model, which encapsulates the application's business logic and data.
Prism includes samples and reference implementations that show how to implement the MVVM pattern in a Silverlight or Windows Presentation Foundation (WPF) application. The Prism Library also provides features that can help you implement the pattern in your own applications. These features embody the most common practices for implementing the MVVM pattern and are designed to support testability and to work well with Expression Blend and Visual Studio.
Class Responsibilities and Characteristics
The MVVM pattern is a close variant of the Presentation Model pattern, optimized to leverage some of the core capabilities of WPF and Silverlight, such as data binding, data templates, commands, and behaviors.
In the MVVM pattern, the view encapsulates the UI and any UI logic, the view model encapsulates presentation logic and state, and the model encapsulates business logic and data. The view interacts with the view model through data binding, commands, and change notification events. The view model queries, observes, and coordinates updates to the model, converting, validating, and aggregating data as necessary for display in the view.
The following illustration shows the three MVVM classes and their interaction.

Like with all separated presentation patterns, the key to using the MVVM pattern effectively lies in understanding the appropriate way to factor your application's code into the correct classes, and in understanding the ways in which these classes interact in various scenarios. The following sections describe the responsibilities and characteristics of each of the classes in the MVVM pattern.
The View Class
The view's responsibility is to define the structure and appearance of what the user sees on the screen. Ideally, the code-behind of a view contains only a constructor that calls the InitializeComponent method. In some cases, the code-behind may contain UI logic code that implements visual behavior that is difficult or inefficient to express in Extensible Application Markup Language (XAML), such as complex animations, or when the code needs to directly manipulate visual elements that are part of the view. You should not put any logic code in the view that you need to unit test. Typically, logic code in the view's code-behind will be tested via a UI automation testing approach.
In Silverlight and WPF, data binding expressions in the view are evaluated against its data context. In MVVM, the view's data context is set to the view model. The view model implements properties and commands to which the view can bind and notifies the view of any changes in state through change notification events. There is typically a one-to-one relationship between a view and its view model.
Typically, views are Control-derived or UserControl-derived classes. However, in some cases, the view may be represented by a data template, which specifies the UI elements to be used to visually represent an object when it is displayed. Using data templates, a visual designer can easily define how a view model will be rendered or can modify its default visual representation without changing the underlying object itself or the behavior of the control that is used to display it.
Data templates can be thought of as views that do not have any code-behind. They are designed to bind to a specific view model type whenever one is required to be displayed in the UI. At run time, the view, as defined by the data template, will be automatically instantiated and its data context set to the corresponding view model.
In WPF, you can associate a data template with a view model type at the application level. WPF will then automatically apply the data template to any view model objects of the specified type whenever they are displayed in the UI. This is known as implicit data templating. In Silverlight, you have to explicitly specify the data template for a view model object within the control that is to display it. In either case, the data template can be defined in-line with the control that uses it or in a resource dictionary outside the parent view and declaratively merged into the view's resource dictionary.
To summarize, the view has the following key characteristics:
  • The view is a visual element, such as a window, page, user control, or data template. The view defines the controls contained in the view and their visual layout and styling.
  • The view references the view model through its DataContext property. The controls in the view are data bound to the properties and commands exposed by the view model.
  • The view may customize the data binding behavior between the view and the view model. For example, the view may use value converters to format the data to be displayed in the UI, or it may use validation rules to provide additional input data validation to the user.
  • The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or via the user's interaction with the UI.
  • The view's code-behind may define UI logic to implement visual behavior that is difficult to express in XAML or that requires direct references to the specific UI controls defined in the view.
The View Model Class
The view model in the MVVM pattern encapsulates the presentation logic and data for the view. It has no direct reference to the view or any knowledge about the view's specific implementation or type. The view model implements properties and commands to which the view can data bind and notifies the view of any state changes through change notification events. The properties and commands that the view model provides define the functionality to be offered by the UI, but the view determines how that functionality is to be rendered.
The view model is responsible for coordinating the view's interaction with any model classes that are required. Typically, there is a one-to many-relationship between the view model and the model classes. The view model may choose to expose model classes directly to the view so that controls in the view can data bind directly to them. In this case, the model classes will need to be designed to support data binding and the relevant change notification events. For more information about this scenario, see the section, Data Binding, later in this topic.
The view model may convert or manipulate model data so that it can be easily consumed by the view. The view model may define additional properties to specifically support the view; these properties would not normally be part of (or cannot be added to) the model. For example, the view model may combine the value of two fields to make it easier for the view to present, or it may calculate the number of characters remaining for input for fields with a maximum length. The view model may also implement data validation logic to ensure data consistency.
The view model may also define logical states the view can use to provide visual changes in the UI. The view may define layout or styling changes that reflect the state of the view model. For example, the view model may define a state that indicates that data is being submitted asynchronously to a web service. The view can display an animation during this state to provide visual feedback to the user.
Typically, the view model will define commands or actions that can be represented in the UI and that the user can invoke. A common example is when the view model provides a Submit command that allows the user submit data to a web service or to a data repository. The view may choose to represent that command with a button so that the user can click the button to submit the data. Typically, when the command becomes unavailable, its associated UI representation becomes disabled. Commands provide a way to encapsulate user actions and to cleanly separate them from their visual representation in the UI.
To summarize, the view model has the following key characteristics:
·         The view model is a non-visual class and does not derive from any WPF or Silverlight base class. It encapsulates the presentation logic required to support a use case or user task in the application. The view model is testable independently of the view and the model.
·         The view model typically does not directly reference the view. It implements properties and commands to which the view can data bind. It notifies the view of any state changes via change notification events via the INotifyPropertyChanged and INotifyCollectionChanged interfaces.
·         The view model coordinates the view's interaction with the model. It may convert or manipulate data so that it can be easily consumed by the view and may implement additional properties that may not be present on the model. It may also implement data validation via the IDataErrorInfo or INotifyDataErrorInfo interfaces.
The view model may define logical states that the view can represent visually to the user.

The Model Class
The model in the MVVM pattern encapsulates business logic and data. Business logic is defined as any application logic that is concerned with the retrieval and management of application data and for making sure that any business rules that ensure data consistency and validity are imposed. To maximize re-use opportunities, models should not contain any use case–specific or user task–specific behavior or application logic.
Typically, the model represents the client-side domain model for the application. It can define data structures based on the application's data model and any supporting business and validation logic. The model may also include the code to support data access and caching, though typically a separate data repository or service is employed for this. Often, the model and data access layer are generated as part of a data access or service strategy, such as the ADO.NET Entity Framework, WCF Data Services, or WCF RIA Services.
Typically, the model implements the facilities that make it easy to bind to the view. This usually means it supports property and collection changed notification through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Models classes that represent collections of objects typically derive from the ObservableCollection<T> class, which provides an implementation of the INotifyCollectionChanged interface.
The model may also support data validation and error reporting through the IDataErrorInfo (or INotifyDataErrorInfo) interfaces. These interfaces allow WPF and Silverlight data binding to be notified when values change so that the UI can be updated. They also enable support for data validation and error reporting in the UI layer.

The model has the following key characteristics:
·     Model classes are non-visual classes that encapsulate the application's data and business logic. They are responsible for managing the application's data and for ensuring its consistency and validity by encapsulating the required business rules and data validation logic.
·     The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
·     The model classes typically provide property and collection change notification events through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. This allows them to be easily data bound in the view. Model classes that represent collections of objects typically derive from the ObservableCollection<T> class.
·     The model classes typically provide data validation and error reporting through either the IDataErrorInfo or INotifyDataErrorInfo interfaces.
·     The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.
Class Interactions

The MVVM pattern provides a clean separation between your application's user interface, its presentation logic, and its business logic and data by separating each into separate classes. Therefore, when you implement MVVM, it is important to factor in your application's code to the correct classes, as described in the previous section.
Well-designed view, view model, and model classes will not only encapsulate the correct type of code and behavior; they will also be designed so that they can easily interact with each other via data binding, commands, and data validation interfaces.
The interactions between the view and its view model are perhaps the most important to consider, but the interactions between the model classes and the view model are also important. The following sections describe the various patterns for these interactions and describe how to design for them when implementing the MVVM pattern in your applications.
Data Binding
Data binding plays a very important role in the MVVM pattern. WPF and Silverlight both provide powerful data binding capabilities. Your view model and (ideally) your model classes should be designed to support data binding so that they can take advantage of these capabilities. Typically, this means that they must implement the correct interfaces.
Silverlight and WPF data binding supports multiple data binding modes. With one-way data binding, UI controls can be bound to a view model so that they reflect the value of the underlying data when the display is rendered. Two-way data binding will also automatically update the underlying data when the user modifies it in the UI.
To ensure that the UI is kept up to date when the data changes in the view model, it should implement the appropriate change notification interface. If it defines properties that can be data bound, it should implement the INotifyPropertyChanged interface. If the view model represents a collection, it should implement the INotifyCollectionChanged interface or derive from the ObservableCollection<T> class that provides an implementation of this interface. Both of these interfaces define an event that is raised whenever the underlying data is changed. Any data bound controls will be automatically updated when these events are raised.
In many cases, a view model will define properties that return objects (and which, in turn, may define properties that return additional objects). WPF and Silverlight data binding supports binding to nested properties via the Path property. Therefore, it is very common for a view's view model to return references to other view model or model classes. All view model and model classes accessible to the view should implement the INotifyPropertyChanged or INotifyCollectionChanged interfaces, as appropriate.
The following sections describe how to implement the required interfaces in order to support data binding within the MVVM pattern.


Wednesday, February 6, 2013

Data Access Object (DAO) Design Pattern

One aspect of the business layer is the data access layer that connects the services with the database. Accessing data varies depending on the source of the data. Access to persistent data varies greatly depending on the type of storage (database, flat files, xml files, and so on) and it even differs from its implementation (for example different SQL-dialects).

Data Access Layer has proven good in separate business logic layer and persistent layer. The DAO design pattern completely  hides the data access implementation from its clients. The interfaces given to client does not changes when the underlying data source mechanism changes. this is the capability which allows the DAO to adopt different access scheme without affecting to business logic or its clients. generally it acts as a adapter between its components and database. The DAO design pattern consists of some factory classes, DAO interfaces and some DAO classes to implement those interfaces.

The goal is to abstract and encapsulate all access to the data and provide an interface. This is called the Data Access Object pattern. In a nutshell, the DAO "knows" which data source (that could be a database, a flat file or even a WebService) to connect to and is specific for this data source (e.g. a OracleDAO might use oracle-specific data types, a WebServiceDAO might parse the incoming and outgoing message etc.).

From the applications point of view, it makes no difference when it accesses a relational database or parses xml files (using a DAO). The DAO is usually able to create an instance of a data object ("to read data") and also to persist data ("to save data") to the datasource.

Applicability / Uses
Use a Data Access Object when:
• you need to access a persistent storage more than one time, especially if you want to exchange the data source later.
• you want to separate a data resource's client interface from its data access mechanisms
• you want to adapt a specific data resource's access API to a generic client interface
• in a larger project, different teams work on different parts of the application: the DAO pattern allows clean separation of concerns.

Related Patterns
Abstract Factory: Applications often use a Factory to select the right DAO implementation at run time.
Transfer Object: The DAO pattern often uses a Transfer Object to send data from the data source to its client and vice versa.

Structure
UML diagram of the sample code:


Sample
In the following example we will create a Data Access Object for saving/retrieving the data of books.
To keep the source-code simple, import declarations and exception-handling is not shown.

public interface BookDAO {
  public void saveBook(Book b);
  public Book loadBook(String isbn);
}


The first implementation flavor will use a simple database (possibly remote) for storing the data:

public class DBBookDAO implements BookDAO {
private PreparedStatement saveStmt;
private PreparedStatement loadStmt;
  public DBBookDAO(String url, String user, String pw) {
    Connection con = DriverManager.getConnection(url, user, pw);
    saveStmt = con.prepareStatement("INSERT INTO books(isbn, title, author) "
                                   +"VALUES (?, ?, ?)");
    loadStmt = con.prepareStatement("SELECT isbn, title, author FROM books "
                                   +"WHERE isbn = ?");
  }
  public Book loadBook(String isbn) {
    Book b = new Book();
    loadStmt.setString(1, isbn);
    ResultSet result = loadStmt.executeQuery();
    if (!result.next()) return null;
   
    b.setIsbn(result.getString("isbn"));
    b.setTitle(result.getString("title"));
    b.setAuthor(result.getString("author"));
    return b;
  }
  public void saveBook(Book b) {
    saveStmt.setString(1, b.getIsbn());
    saveStmt.setString(2, b.getTitle());
    saveStmt.setString(3, b.getAuthor());
    saveStmt.executeUpdate();
  }
}



The second implementation flavor saves every book in its own text-file on the local hard drive:

public class FileBookDAO implements BookDAO {
       
  private String basePath;
  public FileBookDAO(String basePath) {
    this.basePath = basePath;
  }
  public Book loadBook(String isbn) {
    FileReader fr = new FileReader(basePath + isbn);
    BufferedReader br = new BufferedReader(fr);
    Book b = new Book();
    String rIsbn = br.readLine();
    String rTitle = br.readLine();
    String rAuthor = br.readLine();
       
    if (rIsbn.startsWith("ISBN: ")) {
      b.setIsbn(rIsbn.substring("ISBN: ".length()));
    } else {
      return null;
    }
    if (rTitle.startsWith("TITLE: ")) {
      b.setTitle(rTitle.substring("TITLE: ".length()));
    } else {
      return null;
    }
    if (rAuthor.startsWith("AUTHOR: ")) {
      b.setAuthor(rAuthor.substring("AUTHOR: ".length()));
    } else {
      return null;
    }
    return b;
  }
  public void saveBook(Book b) {
    FileWriter fw = new FileWriter(basePath + b.getIsbn() + ".book");
    fw.write("ISBN: " + b.getIsbn());
    fw.write("TITLE: " + b.getTitle());
    fw.write("AUTHOR: " + b.getAuthor());
    fw.close();
  }
}


Data Access Objects (DAOs) :
  • can be used in a large percentage of applications - anywhere data storage is required.
  • hide all details of data storage from the rest of the application.
  • act as an intermediary between your application and the database. They move data back and forth between Java objects and database records.
  • allow ripple effects from possible changes to the persistence mechanism to be confined to a specific area.
For simple DAOs, various implementation styles are possible :
Style 1 - instance methods
MessageDAO dao = new MessageDAO(); List<Message> messages = dao.fetchRecentMessages();
This is the recommended style. Create an ordinary object in the usual way, and use its services.
Style 2 - variation on Style 1
List<Message> messages = new MessageDAO().fetchRecentMessages();
The DAO is created and used on the same line. This style seems a bit less legible than Style 1.
Style 3 - static methods
List<Message> messages = MessageDAO.fetchRecentMessages();
Probably the least desirable. One must exercise care that such classes are thread-safe. This issue usually doesn't exist in Styles 1 and 2, if the DAO has no static members, is short-lived, and there is no possibility of sharing data between threads.

Full DAO Design Pattern
It is common to describe Data Access Objects as an extended design pattern. That design pattern centers on allowing wholesale changes to a datastore mechanism - for example, changing from a relational database to using the file system, or some other means of data storage. It is only required when multiple storage mechanisms must coexist.

It must be stressed that most applications do not need the full DAO design pattern as usually described. Most business applications are deployed with a very particular database in mind. In such cases, allowing a deployer to configure various types of datastore seems entirely superfluous. If your application interacts with only one datastore at a time, then the full DAO pattern is clearly of dubious benefit. Rather, implementing each DAO as a single, ordinary class seems more appropriate and effective.

Minimize ripple effects
Much of object programming is centered on minimizing the ripple effects caused by changes to a program. This is done simply by keeping details secret (information hiding or encapsulation).
The principal ways of doing this are
  • indirection - named constants replacing "magic numbers", for example
  • minimizing visibility - private fields, package-private classes, for example
  • generic references (polymorphism) - using high level references (interfaces or abstract classes) instead of low level references (concrete classes)
All of these techniques accomplish the same thing - they confine knowledge of implementation details to the smallest possible part of a program. That is, they keep a secret of some sort.
Constant and liberal use of the above techniques is recommended.
An interesting quote from chapter one of Design Patterns, regarding the use of generic references :
"This so greatly reduces implementation dependencies between subsystems that it leads to the following principle of reusable object-oriented design :

Program to an interface, not an implementation.
Don't declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class. You will find this to be a common theme of the design patterns in this book."
(They state a second principle as well: "Favor object composition over class inheritance.")

Abstract Factory
Using references to interfaces instead of references to concrete classes is an important way of minimizing ripple effects. The user of an interface reference is always protected from changes to the underlying implementation.
The Abstract Factory pattern is one example of this technique. Users of an Abstract Factory can create families of related objects without any knowledge of their concrete classes. (A typical business application would usually not need to use this technique - it is more suitable for toolkits or libraries.)

Example
An Abstract Factory is a major part of the full Data Access Object scheme. Here, the idea is to allow the business layer to interact with the data layer almost entirely through interface references. The business layer remains ignorant of the concrete classes which implement the datastore.

There are two distinct families of items here :
§  the various datastore implementations (MySql, FileScheme)
§  the various business objects which need persistence (User, Device, etc.)
This corresponds to the two operations which must be done to return a persisted object. The type of datastore is first determined (an implementation of DAOFactory is returned), using a Factory Method.
(This example would be much improved by not having imports of ServletConfig all over the place.)

package myapp.data;

import javax.servlet.ServletConfig;

/**
* Allows selection of a DAOFactory, without the user being
* aware of what choices are available.
*
* This style allows the data layer to make the decision regarding what
* DAOFactory is to be used by the business layer.
*/
public final class DatastoreSelector {

  /**
  * @param aConfig is non-null.
  */
  public static DAOFactory getDAOFactory( ServletConfig aConfig ){
    //demonstrate two implementation styles :
    return stringMappingImpl( aConfig );
    //return classNameImpl( aConfig );
  }

  // PRIVATE //

  /**
  * Use an ad hoc String mapping scheme, and introduce an if-else
  * branch for each alternative.
  */
  private static DAOFactory stringMappingImpl( ServletConfig aConfig ){
    if ( aConfig == null ) {
      throw new IllegalArgumentException("ServletConfig must not be null.");
    }
    //examine the config to extract the db identifier
    final String storageMechanism = aConfig.getInitParameter("DatastoreName");
    if ( storageMechanism.equals("MySql")) {
      return new DAOFactoryMySql( aConfig );
    }
    else if ( storageMechanism.equals("FileScheme") ) {
      return new DAOFactoryFileScheme( aConfig );
    }
    else {
      throw new IllegalArgumentException("Unknown datastore identifier.");
    }
  }

  /**
  * Make direct use of the class name, and use reflection to create the
  * object.
  */
  private static DAOFactory classNameImpl( ServletConfig aConfig ){
    DAOFactory result = null;
    //examine the config to extract the class name
    final String storageClassName = aConfig.getInitParameter("DatastoreClassName");
    try {
      Class storageClass = Class.forName(storageClassName);
      //Class.newInstance can be used only if there is a no-arg constructor ;
      //otherwise, use Class.getConstructor and Constructor.newInstance.
      Class[] types = { javax.servlet.ServletConfig.class };
      java.lang.reflect.Constructor constructor = storageClass.getConstructor(types);
      Object[] params = { aConfig };
      result = (DAOFactory) constructor.newInstance( params );
    }
    catch (Exception ex){
      System.err.println("Cannot create DAOFactory using name: " + storageClassName);
      ex.printStackTrace();
    }
    return result;
  }
}


package myapp.data;

/**
* Returns an implementation of all XXXDAO interfaces.
*/
public interface DAOFactory {

  /**
  * Returns an implementation of DeviceDAO, specific to a
  * particular datastore.
  */
  DeviceDAO getDeviceDAO() throws DataAccessException;

  /**
  * Returns an implementation of UserDAO, specific to a
  * particular datastore.
  */
  UserDAO getUserDAO() throws DataAccessException;
}


Then, each
DAOFactory implementation can return its implementations of the XXXDAO interfaces (DeviceDAO, UserDAO), which are the concrete worker classes which implement persistence.

package myapp.data;

import javax.servlet.ServletConfig;

/**
* Package-private implementation of DAOFactory.
* This is for a MySql database.
*/
final class DAOFactoryMySql implements DAOFactory {

  DAOFactoryMySql( ServletConfig aServletConfig ){
    if ( aServletConfig == null ) {
      throw new IllegalArgumentException("ServletConfig must not be null.");
    }
    fConfig = aServletConfig;
  }

  public UserDAO getUserDAO() throws DataAccessException {
    return new UserDAOMySql(fConfig);
  }

  public DeviceDAO getDeviceDAO() throws DataAccessException {
    return new DeviceDAOMySql(fConfig);
  }

  /// PRIVATE ////
  private final ServletConfig fConfig;
}


package myapp.data;

import javax.servlet.ServletConfig;

/**
* Package-private implementation of DAOFactory.
* This is for an ad hoc file scheme.
*/
final class DAOFactoryFileScheme implements DAOFactory {

  DAOFactoryFileScheme( ServletConfig aServletConfig ){
    if ( aServletConfig == null ) {
      throw new IllegalArgumentException("ServletConfig must not be null.");
    }
    fConfig = aServletConfig;
  }

  public UserDAO getUserDAO() throws DataAccessException {
    return new UserDAOFileScheme(fConfig);
  }

  public DeviceDAO getDeviceDAO() throws DataAccessException {
    return new DeviceDAOFileScheme(fConfig);
  }

  /// PRIVATE ////
  private final ServletConfig fConfig;
}


Here is an example of a
XXXDAO interface, and a toy implementation for a MySql database.

package myapp.data;

import myapp.business.Device;

/**
* The business layer talks to the data layer about storage of Device objects
* through a DeviceDAO reference.
*
* DataAccessException is a wrapper class, which exists only to wrap
* low-level exceptions specific to each storage mechanism (for example,
* SQLException and IOException). When an implementation class throws
* an exception, it is caught, wrapped in a DataAccessException, and then
* rethrown. This protects the business layer from ripple effects caused by
* changes to the datastore implementation.
*/
public interface DeviceDAO {
  Device fetch( String aId ) throws DataAccessException;
  void add( Device aDevice ) throws DataAccessException;
  void change( Device aDevice ) throws DataAccessException;
  void delete( Device aDevice ) throws DataAccessException;
}



package myapp.data;

import myapp.business.Device;
import java.net.InetAddress;
import javax.servlet.ServletConfig;

/**
* An implementation of DeviceDAO which is specific to a MySql database.
*
* This class must be package-private, to ensure that the business layer
* remains unaware of its existence.
*
* Any or all of these methods can be declared as synchronized. It all depends
* on the details of your implementation.
*
* Note that it is often possible to use properties files (or ResourceBundles) to
* keep SQL out of compiled code, which is often advantageous.
*/
final class DeviceDAOMySql implements DeviceDAO {

  DeviceDAOMySql( ServletConfig aConfig ) {
    //..elided
  }

  public Device fetch( String aId ) throws DataAccessException {
    //create a SELECT using aId, fetch a ResultSet, and parse it into a Device
    return null; //toy implementation
  }

  synchronized public void  add( Device aDevice ) throws DataAccessException{
    //parse aDevice into its elements, create an INSERT statement
  }

  synchronized public void change( Device aDevice )  throws DataAccessException{
    //parse aDevice into its elements, create an UPDATE statement
  }

  synchronized public void delete( Device aDevice )  throws DataAccessException {
    //extract the Id from aDevice, create a DELETE statement
  }
}

It is important to note most of the data layer's concrete classes are package-private - only
DatastoreSelector and DataAccessException are public.