Buhake Sindi
Buhake Sindi

Reputation: 89169

Code Design Pattern Structure

I have a dilemna that needs I've been thinking a while but still haven't figured it out how to effectively and efficiently code (design) it.

I have object data that get returns in 3 text-based formats: JSON, XML, ATOM. In JSON, the data can be a JSON Object or JSON array. XML and ATOM are xml.

Based on these 3 formats, I have to create objects (let's say A, B, C, D, E). I thought of having a Builder Pattern to generate these objects, so my interface builder is:

public interface Builder<T, E, A> { //Where E = Element, A is Element array, this is useful for JSON
   public T create(E element);
   public T[] create(A array);
}

public class ABuilder implements Builder<A, JSON, JSONArray> {
  public A create(JSON json) {...}
  public A[] create(JSONArray array) {...}
}

The problem is that I want to create a dynamic Factory/Alternative design pattern that can create an object based on the format....

i.e. I want a functionality such that, I can do

public class Resource {

   public A getA(String formatString) {
      return new Something().createA(formatString); //or something better....
   }
}

Do you have any better way of making this issue possible? Bear in mind, all this is based on the 3 possible formats. The goal is to generate objects dynamically based on the format, without really worrying about the format structure.

Upvotes: 2

Views: 781

Answers (1)

Ami
Ami

Reputation: 1110

I'm not 100% sure I understand what you need, but the first design pattern that came to my mind was Strategy

with this simple and elegant pattern, you can implement a concrete strategy for each implementation you have (xml, json, atom) and you also have a flexible solution that can be easily extended in the future to support new formats without breaking any existing code (that is the Open-Close principle).

so, you would have a Factory method that would provide a "Build"/"Get" method which input would be an enum representing the required format (just an example, you can implement any way you want), and that factory method would use a strategy to actually build the object. that way, the client is 100% unaware of how the object is built, and doesn't even have to know what format it is.

good luck!

Upvotes: 2

Related Questions