Что такое dao java
Шаблон DAO в Java
Узнайте, как реализовать шаблон объекта доступа к данным (DAO) в Java, чтобы изолировать уровни персистентности и бизнес-уровни вашего приложения.
1. Обзор
Функциональность этого API заключается в том, чтобы скрыть от приложения все сложности, связанные с выполнением операций CRUD в базовом механизме хранения. Это позволяет обоим слоям развиваться отдельно, ничего не зная друг о друге.
Дальнейшее чтение:
Введение в весенние данные JPA
Обзор типов каскадов JPA/Hibernate
2. Простая Реализация
Чтобы понять, как работает шаблон DAO, давайте создадим базовый пример.
2.1. Класс Домена
Поскольку наше приложение будет работать с пользователями, нам нужно определить только один класс для реализации его модели домена:
Класс User является простым контейнером для пользовательских данных, поэтому он не реализует никакого другого поведения, заслуживающего внимания.
Конечно, наиболее релевантный выбор дизайна, который нам нужно сделать здесь, заключается в том, как изолировать приложение, использующее этот класс, от любого механизма сохранения, который может быть реализован в какой-то момент.
Ну, это именно та проблема, которую пытается решить шаблон DAO.
2.2. API DAO
Давайте определим базовый слой DAO, чтобы мы могли увидеть, как он может полностью отделить модель домена от уровня персистентности.
2.3. Класс UserDao
Давайте определим пользовательскую реализацию интерфейса Dao :
Конечно, легко рефакторировать другие методы, чтобы они могли работать, например, с реляционной базой данных.
Хотя оба класса User и UserDao сосуществуют независимо в одном приложении, нам все равно нужно посмотреть, как последний можно использовать для сохранения уровня персистентности, скрытого от логики приложения:
3. Использование шаблона С JPA
Среди разработчиков существует общая тенденция полагать, что выпуск JPA снизил функциональность шаблона DAO до нуля, поскольку шаблон становится просто еще одним уровнем абстракции и сложности, реализованным поверх того, который предоставляется менеджером сущностей JPA.
3.1. Класс JpaUserDao
То JpaUserDao класс способен работать с любой реляционной базой данных, поддерживаемой реализацией JPA.
Кроме того, если мы внимательно посмотрим на класс, мы поймем, как использование Composition и Dependency Injection позволяет нам вызывать только методы entity manager, требуемые нашим приложением.
Проще говоря, у нас есть специализированный API для конкретного домена, а не API всего менеджера сущностей.
3.2. Рефакторинг пользовательского класса
В этом случае мы будем использовать Hibernate в качестве реализации JPA по умолчанию, поэтому мы соответствующим образом рефакторингуем класс User :
3.3. Программная загрузка менеджера сущностей JPA
В большинстве случаев мы достигаем этого с помощью типичного “persistence.xml” файл, что является стандартным подходом.
3.4. Класс UserApplication
Наконец, давайте проведем рефакторинг исходного Пользовательского приложения класса, чтобы он мог работать с экземпляром JpaUserDao и выполнять операции CRUD над сущностями User :
Даже если пример действительно довольно ограничен, он остается полезным для демонстрации того, как интегрировать функциональность шаблона DAO с той, которую предоставляет менеджер сущностей.
Кроме того, мы могли бы поменять MySQL на любую другую СУБД (и даже на плоскую базу данных) в дальнейшем, и все же наше приложение продолжало бы работать, как ожидалось, благодаря уровню абстракции, обеспечиваемому интерфейсом Dao и менеджером сущностей.
4. Заключение
В этой статье мы подробно рассмотрели ключевые концепции шаблона DAO, как реализовать его в Java и как использовать его поверх менеджера сущностей JPA.
Data Access Object
Also Known As DAO
Brief Description
Code that depends on specific features of data resources ties together business logic with data access logic. This makes it difficult to replace or modify an application’s data resources.
The Data Access Object (or DAO) pattern:
The DAO pattern allows data access mechanisms to change independently of the code that uses the data.
Detailed Description
See the Core J2EE TM Patterns
Detailed Example
The Java Pet Store sample application uses the DAO pattern both for database vendor-neutral data access, and to represent XML data sources as objects.
The following code excerpts illustrate how the sample application uses the DAO pattern to separate business logic from data resource access mechanisms:
For example, the sample application uses factory class CatalogDAOFactory to select the class that implements the DAO interface for the catalog. Figure 2 below presents a structure diagram of the Data Access Object design pattern using a factory to select a DAO implementation.
Figure 2. A pluggable DAO
This approach is more flexible than using a hard-coded class. To add a new type of data source, an application developer would simply create a class that implements CatalogDAO in terms of the new data source type, specify the implementing class’s name in the environment entry, and re-deploy. The factory would create an instance of the new DAO class, and the application would use the new data source type.
The sample application reduces redundant code by using a «generic DAO» that externalizes the SQL for different JDBC data sources. Figure 3 below shows how the sample application uses an XML file to specify the SQL for different JDBC data sources.
Figure 3. Externalizing DAO SQL
Method GenericCatalogDAO.getCategory chooses the SQL corresponding to the configured database type, and uses it to fetch a category from the database via JDBC. The following code excerpt shows shows the implementation of the method.
This strategy supports multiple JDBC databases with a single DAO class. It both decreases redundant code, and makes new database types easier to add. To support a new database type, a developer simply adds the SQL statements for that database type to the XML file, updates the environment entry to use the new type, and redeploys.
The pluggable DAO and generic DAO strategies can be used separately. If you know that a DAO class will only ever use JDBC databases (for example), the generic DAO class can be hardwired into the application, instead of selected by a factory. For maximum flexibility, the sample application uses both a factory method and a generic DAO.
The screen definitions mechanism in the sample application provides an example of a concrete Data Access Object representing an underlying, non-database resource (an XML file).
Figure 1. Data Access Object providing access to XML data source
Figure 1 shows a structure diagram of the ScreenDefinitionDAO managing the loading and interpretation of XML data that defines application screens.
Screens screenDefinitions = ScreenDefinitionDAO.loadScreenDefinitions(screenDefinitionURL);
The code fragment above shows how loadScreenDefinitions loads screen definitions using DOM interfaces, while hiding that fact from clients of the class. A client of this class can expect to receive a Screens object regardless of how those screens are loaded from persistent storage. Method getScreens handles all of the DOM-specific details of loading a screen from an XML file.
Использование паттерна data access object в клиентском приложении
Всем привет! В этой статье я поделюсь своим опытом по работе с базой данных в приложении для Android. Это будет один из вариантов реализации паттерна data access object на языке Java.
Постановка задачи
Заказчик, который занимается предстраховыми осмотрами автомобилей, хочет автоматизировать рабочий процесс. Задача приложения — собирать и передавать на обработку данные об автомобиле.
Проектирование показало, что у приложения будет 3 модуля:
Сущности
Доступ к данным
Выделим для этих сущностей 3 вида доступа. В данном случае это будут следующие интерфейсы:
Далее создадим data access object, который предоставляет доступы. Этот интерфейс будет выглядеть так:
Теперь у нас есть все необходимые виды доступа, но пока они не запрашивают и не изменяют данные.
Модели данных
Готовый осмотр будет состоять из элементов, а элементы из данных. Нужно реализовать возможность получения осмотра по ключу, построение списка черновиков осмотров, списка готовых осмотров, а также возможность удалить осмотр. Таким образом, для всех подсущностей осмотра создадим модели:
Теперь передадим доступам их модели:
Теперь наш data access object готов.
Использование data access object
У нас есть три модуля. Каждый из них получит доступ только к той области базы данных, которая необходима для выполнения его задач.
Для сравнения посмотрите на код, который используется для получения данных, если не использовать DAO:
Обратите внимание, что класс неявно получает зависимость от конкретной реализации SQLite. Более того, он получает доступ ко всем частям базы данных, хотя не должен иметь возможности читать, изменять и удалять данные вне его круга задач. А вот как выглядит реализация аналогичной задачи с применением DAO:
Тестирование
Реализация
Заключение
Используя DAO, можно удобно разделять уровни доступа при работе с базой данных, чётко видеть эти уровни доступа и легко оперировать ими, не привязываясь к конкретной реализации хранения данных. Это позволяет применять такой подход вместе с TDD и точнее настраивать реализацию работы с БД (без изменений в других модулях) или полностью заменить одну реализацию на другую.
The DAO Pattern in Java
Last modified: November 10, 2021
Get started with Spring Data JPA through the reference Learn Spring Data JPA course:
1. Overview
The Data Access Object (DAO) pattern is a structural pattern that allows us to isolate the application/business layer from the persistence layer (usually a relational database but could be any other persistence mechanism) using an abstract API.
The API hides from the application all the complexity of performing CRUD operations in the underlying storage mechanism. This permits both layers to evolve separately without knowing anything about each other.
In this tutorial, we’ll take a deep dive into the pattern’s implementation, and we’ll learn how to use it for abstracting calls to a JPA entity manager.
Further reading:
Introduction to Spring Data JPA
Overview of JPA/Hibernate Cascade Types
2. A Simple Implementation
To understand how the DAO pattern works, let’s create a basic example.
Let’s say that we want to develop an application that manages users. We want to keep the application’s domain model completely agnostic about the database. So, we’ll create a simple DAO class that will take care of keeping these components neatly decoupled from each other.
2.1. The Domain Class
As our application will work with users, we need to define just one class for implementing its domain model:
The User class is just a plain container for user data, so it doesn’t implement any other behavior worth stressing.
Of course, the important design choice here is how to keep the application using this class isolated from any persistence mechanism that could be implemented.
And that’s exactly the issue that the DAO pattern attempts to address.
2.2. The DAO API
Let’s define a basic DAO layer so we can see how it can keep the domain model completely decoupled from the persistence layer.
From a bird’s-eye view, it’s clear that the Dao interface defines an abstract API that performs CRUD operations on objects of type T.
Due to the high level of abstraction that the interface provides, it’s easy to create a concrete, fine-grained implementation that works with User objects.
2.3. The UserDao Class
Let’s define a user-specific implementation of the Dao interface:
The UserDao class implements all the functionality required for fetching, updating and removing User objects.
For simplicity’s sake, the users List acts like an in-memory database, which is populated with a couple of User objects in the constructor.
Of course, it’s easy to refactor the other methods so they can work, for instance, with a relational database.
While both the User and UserDao classes coexist independently within the same application, we still need to see how the latter can be used for keeping the persistence layer hidden from application logic:
The example is contrived, but it shows in a nutshell the motivations behind the DAO pattern. In this case, the main method just uses a UserDao instance to perform CRUD operations on a few User objects.
The most relevant facet of this process is how UserDao hides from the application all the low-level details on how the objects are persisted, updated and deleted.
3. Using the Pattern With JPA
There’s a tendency among developers to think that the release of JPA downgraded to zero the DAO pattern’s functionality. The pattern becomes just another layer of abstraction and complexity on top of the one provided by JPA’s entity manager.
This is true in some scenarios. Even so, we sometimes just want to expose to our application only a few domain-specific methods of the entity manager’s API. The DAO pattern has its place in such cases.
3.1. The JpaUserDao Class
Let’s create a new implementation of the Dao interface to see how it can encapsulate the functionality that JPA’s entity manager provides out of the box:
The JpaUserDao class can work with any relational database supported by the JPA implementation.
Also, if we look closely at the class, we’ll realize how the use of Composition and Dependency Injection allows us to call only the entity manager methods required by our application.
Simply put, we have a domain-specific tailored API, rather than the entire entity manager’s API.
3.2. Refactoring the User Class
In this case, we’ll use Hibernate as the JPA default implementation, so we’ll refactor the User class accordingly:
3.3. Bootstrapping a JPA Entity Manager Programmatically
Assuming that we already have a working instance of MySQL running either locally or remotely and a database table “users” populated with some user records, we need to get a JPA entity manager so we can use the JpaUserDao class for performing CRUD operations in the database.
In most cases, we accomplish this via the typical persistence.xml file, which is the standard approach.
In this case, we’ll take an XML-less approach and get the entity manager with plain Java through Hibernate’s handy EntityManagerFactoryBuilderImpl class.
For a detailed explanation on how to bootstrap a JPA implementation with Java, please check this article.
3.4. The UserApplication Class
Finally, let’s refactor the initial UserApplication class so it can work with a JpaUserDao instance and run CRUD operations on the User entities:
The example here is pretty limited. But it’s useful for showing how to integrate the DAO pattern’s functionality with the one that the entity manager provides.
In most applications, there’s a DI framework, which is responsible for injecting a JpaUserDao instance into the UserApplication class. For simplicity’s sake, we’ve omitted the details of this process.
The most relevant point to stress here is how the JpaUserDao class helps to keep the UserApplication class completely agnostic about how the persistence layer performs CRUD operations.
In addition, we could swap MySQL for any other RDBMS (and even for a flat database) further down the road, and our application would continue working as expected, thanks to the level of abstraction provided by the Dao interface and the entity manager.
4. Conclusion
In this article, we took an in-depth look at the DAO pattern’s key concepts. We saw how to implement it in Java and how to use it on top of JPA’s entity manager.
As usual, all the code samples shown in this article are available over on GitHub.
Что такое dao java
Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.
Problem
Many real-world Java 2 Platform, Enterprise Edition (J2EE) applications need to use persistent data at some point. For many applications, persistent storage is implemented with different mechanisms, and there are marked differences in the APIs used to access these different persistent storage mechanisms. Other applications may need to access data that resides on separate systems. For example, the data may reside in mainframe systems, Lightweight Directory Access Protocol (LDAP) repositories, and so forth. Another example is where data is provided by services through external systems such as business-to-business (B2B) integration systems, credit card bureau service, and so forth.
Typically, applications use shared distributed components such as entity beans to represent persistent data. An application is considered to employ bean-managed persistence (BMP) for its entity beans when these entity beans explicitly access the persistent storage-the entity bean includes code to directly access the persistent storage. An application with simpler requirements may forego using entity beans and instead use session beans or servlets to directly access the persistent storage to retrieve and modify the data. Or, the application could use entity beans with container-managed persistence, and thus let the container handle the transaction and persistent details.
Applications can use the JDBC API to access data residing in a relational database management system (RDBMS). The JDBC API enables standard access and manipulation of data in persistent storage, such as a relational database. The JDBC API enables J2EE applications to use SQL statements, which are the standard means for accessing RDBMS tables. However, even within an RDBMS environment, the actual syntax and format of the SQL statements may vary depending on the particular database product.
Forces
Components such as bean-managed entity beans, session beans, servlets, and other objects like helpers for JSP pages need to retrieve and store information from persistent stores and other data sources like legacy systems, B2B, LDAP, and so forth.
Persistent storage APIs vary depending on the product vendor. Other data sources may have APIs that are nonstandard and/or proprietary. These APIs and their capabilities also vary depending on the type of storage-RDBMS, object-oriented database management system (OODBMS), XML documents, flat files, and so forth. There is a lack of uniform APIs to address the requirements to access such disparate systems.
Components typically use proprietary APIs to access external and/or legacy systems to retrieve and store data.
Portability of the components is directly affected when specific access mechanisms and APIs are included in the components.
Components need to be transparent to the actual persistent store or data source implementation to provide easy migration to different vendor products, different storage types, and different data source types.
Solution
Use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data.
The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. The business component that relies on the DAO uses the simpler interface exposed by the DAO for its clients. The DAO completely hides the data source implementation details from its clients. Because the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to adapt to different storage schemes without affecting its clients or business components. Essentially, the DAO acts as an adapter between the component and the data source.
Structure
Figure 9.1 shows the class diagram representing the relationships for the DAO pattern.
Figure 9.1 Data Access Object
Participants and Responsibilities
Figure 9.2 contains the sequence diagram that shows the interaction between the various participants in this pattern.
Figure 9.2 Data Access Object sequence diagram
BusinessObject
The BusinessObject represents the data client. It is the object that requires access to the data source to obtain and store data. A BusinessObject may be implemented as a session bean, entity bean, or some other Java object, in addition to a servlet or helper bean that accesses the data source.
DataAccessObject
The DataAccessObject is the primary object of this pattern. The DataAccessObject abstracts the underlying data access implementation for the BusinessObject to enable transparent access to the data source. The BusinessObject also delegates data load and store operations to the DataAccessObject.
DataSource
This represents a data source implementation. A data source could be a database such as an RDBMS, OODBMS, XML repository, flat file system, and so forth. A data source can also be another system (legacy/mainframe), service (B2B service or credit card bureau), or some kind of repository (LDAP).
TransferObject
This represents a Transfer Object used as a data carrier. The DataAccessObject may use a Transfer Object to return data to the client. The DataAccessObject may also receive the data from the client in a Transfer Object to update the data in the data source.
Strategies
Automatic DAO Code Generation Strategy
Since each BusinessObject corresponds to a specific DAO, it is possible to establish relationships between the BusinessObject, DAO, and underlying implementations (such as the tables in an RDBMS). Once the relationships are established, it is possible to write a simple application-specific code-generation utility that generates the code for all DAOs required by the application. The metadata to generate the DAO can come from a developer-defined descriptor file. Alternatively, the code generator can automatically introspect the database and provide the necessary DAOs to access the database. If the requirements for DAOs are sufficiently complex, consider using third-party tools that provide object-to-relational mapping for RDBMS databases. These tools typically include GUI tools to map the business objects to the persistent storage objects and thereby define the intermediary DAOs. The tools automatically generate the code once the mapping is complete, and may provide other value-added features such as results caching, query caching, integration with application servers, integration with other third-party products (e.g., distributed caching), and so forth.
Factory for Data Access Objects Strategy
The DAO pattern can be made highly flexible by adopting the Abstract Factory [GoF] and the Factory Method [GoF] patterns (see «Related Patterns» in this chapter).
When the underlying storage is not subject to change from one implementation to another, this strategy can be implemented using the Factory Method pattern to produce a number of DAOs needed by the application. The class diagram for this case is shown in Figure 9.3.
Figure 9.3 Factory for Data Access Object strategy using Factory Method
When the underlying storage is subject to change from one implementation to another, this strategy may be implemented using the Abstract Factory pattern. The Abstract Factory can in turn build on and use the Factory Method implementation, as suggested in Design Patterns: Elements of Reusable Object-Oriented Software [GoF]. In this case, this strategy provides an abstract DAO factory object (Abstract Factory) that can construct various types of concrete DAO factories, each factory supporting a different type of persistent storage implementation. Once you obtain the concrete DAO factory for a specific implementation, you use it to produce DAOs supported and implemented in that implementation.
The class diagram for this strategy is shown in Figure 9.4. This class diagram shows a base DAO factory, which is an abstract class that is inherited and implemented by different concrete DAO factories to support storage implementation-specific access. The client can obtain a concrete DAO factory implementation such as RdbDAOFactory and use it to obtain concrete DAOs that work with that specific storage implementation. For example, the data client can obtain an RdbDAOFactory and use it to get specific DAOs such as RdbCustomerDAO, RdbAccountDAO, and so forth. The DAOs can extend and implement a generic base class (shown as DAO1 and DAO2) that specifically describe the DAO requirements for the business object it supports. Each concrete DAO is responsible for connecting to the data source and obtaining and manipulating data for the business object it supports.
The sample implementation for the DAO pattern and its strategies is shown in the «Sample Code» section of this chapter.
Figure 9.4 Factory for Data Access Object strategy using Abstract Factory
The sequence diagram describing the interactions for this strategy is shown in Figure 9.5.
Figure 9.5 Factory for Data Access Objects using Abstract Factory sequence diagram
Consequences
Enables Transparency Business objects can use the data source without knowing the specific details of the data source’s implementation. Access is transparent because the implementation details are hidden inside the DAO.
Enables Easier Migration A layer of DAOs makes it easier for an application to migrate to a different database implementation. The business objects have no knowledge of the underlying data implementation. Thus, the migration involves changes only to the DAO layer. Further, if employing a factory strategy, it is possible to provide a concrete factory implementation for each underlying storage implementation. In this case, migrating to a different storage implementation means providing a new factory implementation to the application.
Reduces Code Complexity in Business ObjectsBecause the DAOs manage all the data access complexities, it simplifies the code in the business objects and other data clients that use the DAOs. All implementation-related code (such as SQL statements) is contained in the DAO and not in the business object. This improves code readability and development productivity.
Centralizes All Data Access into a Separate Layer Because all data access operations are now delegated to the DAOs, the separate data access layer can be viewed as the layer that can isolate the rest of the application from the data access implementation. This centralization makes the application easier to maintain and manage.
Not Useful for Container-Managed Persistence Because the EJB container manages entity beans with container-managed persistence (CMP), the container automatically services all persistent storage access. Applications using container-managed entity beans do not need a DAO layer, since the application server transparently provides this functionality. However, DAOs are still useful when a combination of CMP (for entity beans) and BMP (for session beans, servlets) is required.
Adds Extra Layer The DAOs create an additional layer of objects between the data client and the data source that need to be designed and implemented to leverage the benefits of this pattern. But the benefit realized by choosing this approach pays off for the additional effort.
Needs Class Hierarchy Design When using a factory strategy, the hierarchy of concrete factories and the hierarchy of concrete products produced by the factories need to be designed and implemented. This additional effort needs to be considered if there is sufficient justification warranting such flexibility. This increases the complexity of the design. However, you can choose to implement the factory strategy starting with the Factory Method pattern first, and then move towards the Abstract Factory if necessary.
Sample Code
Implementing Data Access Object pattern
An example DAO code for a persistent object that represents Customer information is shown in Example 9.4. The CloudscapeCustomerDAO creates a Customer Transfer Object when the findCustomer() method is invoked.
The sample code to use the DAO is shown in Example 9.6. The class diagram for this example is shown in Figure 9.6.
Figure 9.6 Implementing the DAO pattern
Implementing Factory for Data Access Objects Strategy
Using Factory Method Pattern
Consider an example where we are implementing this strategy in which a DAO factory produces many DAOs for a single database implementation (e.g., Oracle). The factory produces DAOs such as CustomerDAO, AccountDAO, OrderDAO, and so forth. The class diagram for this example is shown in Figure 9.7.
Figure 9.7 Implementing the Factory for DAO strategy using Factory Method
The example code for the DAO factory (CloudscapeDAOFactory) is listed in Example 9.2.
Using Abstract Factory Pattern
Consider an example where we are considering implementing this strategy for three different databases. In this case, the Abstract Factory pattern can be employed. The class diagram for this example is shown in Figure 9.8. The sample code in Example 9.1 shows code excerpt for the abstract DAOFactory class. This factory produces DAOs such as CustomerDAO, AccountDAO, OrderDAO, and so forth. This strategy uses the Factory Method implementation in the factories produced by the Abstract Factory.
Figure 9.8 Implementing the Factory for DAO strategy using Abstract Factory Example 9.1 Abstract DAOFactory Class
The sample code for CloudscapeDAOFactory is shown in Example 9.2. The implementation for OracleDAOFactory and SybaseDAOFactory are similar except for specifics of each implementation, such as JDBC driver, database URL, and differences in SQL syntax, if any.
Example 9.2 Concrete DAOFactory Implementation for Cloudscape
The CustomerDAO interface shown in Example 9.3 defines the DAO methods for Customer persistent object that are implemented by all concrete DAO implementations, such as CloudscapeCustomerDAO, OracleCustomerDAO, and SybaseCustomerDAO. Similar, but not listed here, are AccountDAO and OrderDAO interfaces that define the DAO methods for Account and Order business objects respectively.
Example 9.3 Base DAO Interface for Customer
The CloudscapeCustomerDAO implements the CustomerDAO as shown in Example 9.4. The implementation of other DAOs, such as CloudscapeAccountDAO, CloudscapeOrderDAO, OracleCustomerDAO, OracleAccountDAO, and so forth, are similar.
Example 9.4 Cloudscape DAO Implementation for Customer
The Customer Transfer Object class is shown in Example 9.5. This is used by the DAOs to send and receive data from the clients. The usage of Transfer Objects is discussed in detail in the Transfer Object pattern.
Example 9.5 Customer Transfer Object
Example 9.6 shows the usage of the DAO factory and the DAO. If the implementation changes from Cloudscape to another product, the only required change is the getDAOFactory() method call to the DAO factory to obtain a different factory.
Related Patterns
Transfer Object A DAO uses Transfer Objects to transport data to and from its clients.
Factory Method [GoF] and Abstract Factory [GoF] The Factory for Data Access Objects Strategy uses the Factory Method pattern to implement the concrete factories and its products (DAOs). For added flexibility, the Abstract Factory pattern may be employed as discussed in the strategies.
Broker [POSA1] The DAO pattern is related to the Broker pattern, which describes approaches for decoupling clients and servers in distributed systems. The DAO pattern more specifically applies this pattern to decouple the resource tier from clients in another tier, such as the business or presentation tier
Contact Us © 2001-2002 Sun Microsystems, Inc. All Rights Reserved.