Design template for saving / loading an object in a different format

I have an object: X, which can be saved or loaded in various formats: TXT, PDF, HTML, etc.

What is the best way to handle this situation? Add a couple of methods in X for each format, create a new class for each format, or create (as I believe) a better solution?

+4
source share
5 answers

I would choose a strategy template. For instance:

interface XStartegy { X load(); void save(X x); } class TxtStrategy implements XStartegy { //...implementation... } class PdfStrategy implements XStartegy { //...implementation... } class HtmlStrategy implements XStartegy { //...implementation... } class XContext { private XStartegy strategy; public XContext(XStartegy strategy) { this.strategy = strategy; } public X load() { return strategy.load(); } public void save(X x) { strategy.save(x); } } 
+3
source

I agree with @DarthVader, although it is better to write in Java

 public class XDocument implements IDocument { ... 

You can also use an abstract class if you have a lot in common with documents, and abstract save() , which is implemented only in subclasses, is called in the general methods of the base class.

+1
source

I would go with a Factory pattern. It looks like you can use inheritance / polymorphism with generics. You can even inject dependencies if you go with a similar design as follows.

 public interface IDocument { void Save(); } public class Document : IDocument { } public class PdfDocument: IDocument { public void Save(){//...} } public class TxtDocument: IDocument { public void Save(){//...} } public class HtmlDocument : IDocument { public void Save(){//...} } 

then in another class you can do this:

 public void SaveDocument(T document) where T : IDocument { document.save(); } 
0
source

It depends on your objects, but it is possible that a visitor template can be used here (http://en.wikipedia.org/wiki/Visitor_pattern). There are different visitors (PDFVisitor, HHTMLVisitor, etc.) who know how to serialize the parts of your objects that they visit.

0
source

Instead, I propose a strategy template. You always save and restore, the only difference is how you do it (your strategy). Thus, you have the save() and restore() methods that carry over to various FormatStrategy objects that you can plug in and play at runtime.

0
source

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


All Articles