views:

76

answers:

3

Hi,

Until now I've been used to using DAOs to retrieve information from databases. Other sources of data are possible though and I'm wondering if and how the pattern could be applied in general.

For example, I'm now working on an application that fetches XML on the web. The XML file could be considered as a data source and the actual fetching is similar in principle to a database request. I'm not quite sure how the DAO could be structured though.

Any views on the subject are welcome.

+4  A: 

See for example "Encapsulating non-database data resources as DAO classes" section here:

http://java.sun.com/blueprints/patterns/DAO.html

DVK
Thanks. The following link from that page should prove useful:http://java.sun.com/blueprints/code/jps131/src/com/sun/j2ee/blueprints/waf/view/template/ScreenDefinitionDAO.java.html
James P.
+4  A: 

Since DAOs only express CRUD operations in terms of objects, without ever referring to their data source, I can't see why this is a question. If your DAO begins with an interface that meets those criteria clients need not know whether or not it's implemented in terms of XML or a relational database.

.NET's LINQ manages to turn that trick. Maybe it's another design that you can emulate for this problem.

duffymo
Ok, so it's the interface that's the most important. Is it a good practise to put the code that actually gets the data in the DAO or should this be put in a separate class? In the case of an XML file this involves the use of URLConnection and DataInputStream. There is also some threading since more than one file is to be retrieved in one go.
James P.
Getting the data seems like it belongs in the implementation to me. More than one file? You're joining two XML sources into one set of objects?
duffymo
Well, I'm writing a sort of RSS feed aggregator at the moment. As such, I'm wondering if the DAO pattern is really justified. Plus, it gets more confusing for me if I contemplate retrieving data (ex: currency values) from the web and then saving it locally.
James P.
+2  A: 

Your DAO offers generic methods that are - as you already said - independent of any datasource. Therefore you create a DAO interface and then just provide different implementations. Other classes then only use the DAO interface.

public interface DummyDao
{
    Dummy getDummy(String id);
}

public class SqlDummyDao implements DummyDao
{
    public Dummy getDummy(String id)
    {
        // Do sql stuff and mapping to dummy bean here
    }
}

public class XmlDummyDao implements DummyDao
{
    public Dummy getDummy(String id)
    {
        XmlDocument xml = fetchRemoteXml(id);
        // do xml mapping to dummy bean here
    }
}
Daff