Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What design pattern should I use for import/export?

I have a calendar event object. I have plans to make it compatible with CalDAV/iCal/vCal protocols/file formats, which require the event be serialized and de-serialized to and from different formats.

I could write an ImportICal, ExportICal, ImportVCal, ExportVCal, etc. set of methods, but that doesn't seem like a very good approach, because what if the vCal format is updated, etc.

Has anyone dealt with this type of import/export situation before? If so, what design pattern (if any) is generally best?

Thanks for your help!

like image 620
Brandon Montgomery Avatar asked Nov 17 '09 22:11

Brandon Montgomery


People also ask

Which is the most used design pattern in Java?

Factory Design Pattern One of the most popular design patterns used by software developers is a factory method. It is a creational pattern that helps create an object without the user getting exposed to creational logic.

What are the design patterns used in project?

4 Design Patterns You Should Know for Web Development: Observer, Singleton, Strategy, and Decorator.

What are design patterns types?

Design patterns are divided into three fundamental groups: Behavioral, Creational, and. Structural.


1 Answers

I am not particulary familiar with those formats but I'd create an simple data transfer object that represents your genereric calendar event object. It does nothing but holding the data (pseudocode):

class CalendarEvent
{
    DateTime Date { get; }
    string Title { get; }
    string Description { get; }
}

Then you create an interface for CalendarEventReader and CalendarEventWriter (it's Strategy pattern and maybe the Builder pattern, sort of):

interface ICalendarEventReader
{
     CalendarEvent Read(Stream data);
     // Add additional methods if needed e.g.:
     string GetTitleOnly(Stream data);
}
interface ICalendarEventWriter
{
     Stream Write(CalendarEvent event);
     // Add additional methods if needed e.g.:
     Stream WriteSummaryOnly(CalendarEvent event);
}

Then have actual implementations implement the above interfaces. One for each format. You can even think about having reader and writer in the same class:

class CalDavConverter : ICalenderEventWriter, ICalendarEventReader
{
    ...
}

You'd then have a Repository (it's the Factory pattern maybe with Singleton) that maintains a list of ICalenderEventReader/Writer implementations for the different formats:

static class CalenderEventConverterRepository
{
    static ICalendarEventReader GetReader(string formatName /*or any other data upon wich to decide wich format is needed*/)
    { 
    ...
    }

    static ICalendarEventReader GetWriter(string formatName /*or any other data upon wich to decide wich format is needed*/)
    { 
    ...
    }
}
like image 106
bitbonk Avatar answered Sep 20 '22 13:09

bitbonk