Elegir el patrón de diseño adecuado para la conversión y validación de datos

I have the below architecture.

  1. Get data from User
  2. Validar datos
  3. Almacenar datos en db

To simplify, let us assume data is of type Invoice. I have defined Invoice as an interface

Invoice () {
getInvoiceId ();

In one of my implementations, the input from user is xml and in another it is json Similarly I have two databases, one stores the invoice as xml and another as json

So I implement the Invoice interface twice as

InvoiceXml () {
xml _invoiceData;
getInvoiceId() {
return _invoiceData.id;

InvoiceJson () {
json _invoiceData;
getInvoiceId() {
return _invoiceData.id;

Now my main class accepts an instance of Invoice interface.

main(Validator validator, DAO db) 
   Invoice invoice = inputs.getInvoice();
   if (invoice instanceOf InvoiceXml {
   else //similar for Json

Now the concern I have is that validator and db both actually need the json/xml representation of invoice but since I depend only on the Invoice interface I have to downcast Invoice before passing it to validate and db.

I am not sure of how to design this in a better way. I was thinking of changing the Invoice interface to a POJO but there are many fields on the Invoice (getInvoiceId and getInvoiceAmount are the common ones used) so I have to internally store the invoice as an xml or json value only.

preguntado el 31 de julio de 12 a las 15:07

1 Respuestas

One approach could be adding validate método para Invoice interface and implement it properly on implementations InvoiceXml y InvoiceJson. But that merge two concepts: model and validation. Another approach to have interface Validator con metodo validate to separate from model and implement two datasource specific validation methods.

Respondido 31 Jul 12, 15:07

I have a prototype using a Validator interface but how do I enforce the criteria that I have to use XmlValidator when I want to validate InvoiceXml without needing to downcast - Arvind

interfaz. invoice.validate(Validator v) and xmlImplementation validate(Validator v) { v.validateXml(this) } - contratiempo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.