[ACCEPTED]-What design pattern should I use for import/export?-oop

Accepted answer
Score: 24

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

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

Then you create an 9 interface for CalendarEventReader and CalendarEventWriter 8 (it's Strategy pattern and maybe the Builder pattern, sort 7 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 6 the above interfaces. One for each format. You 5 can even think about having reader and writer 4 in the same class:

class CalDavConverter : ICalenderEventWriter, ICalendarEventReader
{
    ...
}

You'd then have a Repository 3 (it's the Factory pattern maybe with Singleton) that maintains 2 a list of ICalenderEventReader/Writer implementations 1 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*/)
    { 
    ...
    }
}
Score: 1

Usual way to arrange multiple implementations 2 (calendar protocols in your case) with a 1 single common interface is Bridge Pattern.

Score: 0

If the vCal format is updated, you will 14 have to change whatever code you have written 13 whichever design pattern you use (unless 12 they decide to switch to something like 11 ASN.1 where upgrades are baked in).

I would 10 create a format interface with import and 9 export methods, and possibly metadata and 8 methods for testing whether a random bit 7 of XML is likely to be that format. Then 6 for each different format, you have an object 5 which implements that interface. This is 4 sort of a 'strategy design pattern', but 3 each format represents several strategies 2 for doing a cohesive set of things (import,export,detection) rather 1 than having separate strategy objects.

More Related questions