What design pattern do the converters share?

To convert a Java object model to XML, I use the following design:

For different types of objects (for example, primitive types, collections, zeros, etc.) I define each my own converter , which acts in relation to this type, Thus, it can be easily expanded without adding code to the huge if- construct else-then.

Converters are selected using a method that checks whether an object is convertible at all and using priority order. The order of priorities is important, so let's say that List not convertible by POJO converter, although it can be convertible as such, it would be more appropriate to use the collection converter.

What is a design template?

I can only think of the resemblance to a team template.

+4
source share
1 answer

Well, you can start by wanting to classify what you want to do (output an XML file, convert something). Design templates fall into three categories:

In this case, you have two types of classes: xml-writer and some converters. The xml writer is basically the creator (he creates the file)

 XmlWriter writer = new XmlWriter(); writer.writeHeader(); for (Item item : xmlitems) { writer.write(convert(item)); } writer.close(); 

Now the actual conversion of the class to xml is done by several classes. You mentioned that you have a method that checks classes and directs them to a specific converter. This class can be claimed to create a new instance of something, so it falls into the creation templates.

There are three types of templates suitable for IMO.

  • An abstract factory template that provides an interface for creating related or dependent objects without specifying specific classes of objects.

  • A Builder template that separates the construction of a complex object from its presentation so that the same building process can create a different view.

  • Factory is a method template that allows a class to defer an instance to subclasses.

Source: Wikipedia

Any of them suits me. The linker template is suitable because the implementation is similar to

 public interface Converter { void convert(Item item); XmlTextNode getResult(); // get xml code } 

i.e. you give the class something and you get the result.

The factory sample is suitable as you defer the instance to another class (your redirection method that you talked about)

 public XmlTextNode convert(Item item) { if (item instanceof ConcreteItem) { return new ConcreteConverter(item).getResult(); } throw new InvalidOperationException("Invalid convert type"); } 

In any case, the actual type of the returned item is not important. It depends a little on where you want to "define a template". This is a method in which you switch types, or into a create / conversion class.

And again, I am not an expert in this matter.

+3
source

Source: https://habr.com/ru/post/1436168/


All Articles