Java – design pattern for describing a variable subpart of a config file

design-patternsidiomsjava

Suppose I have an XML config file like the following:

<myapp>
    <settings/>

    <output>

        <mailto>mail service configuration parameters</mailto>
                           OR            
        <smsto>sms service configuration parameters</smsto>        

    <output>

While the settings node will have always the same structure, the output node may have different structures, depending on whether it is a mail or an SMS output.

The Java classes will be:

class MyAppConfig {

    String settingXXX;

    {what type?} output;

}

Obviously I will have a class MailTo {} and a class SmsTo {}.

Since output may either be a MailTo or a SmsTo object, it can be:

  • an Object type, since MailTo and SmsTo don't have any superclass in
    common.
  • an Output interface, that in turn is implemented by MailTo and
    SmsTo. Since MailTo and SmsTo don't have anything in common, Output interface will be empty and will "collapse" to a marker interface.

I think that, given this situation, this is the only implementation possible.
The client code will typecast Object or Output to MailTo or SmsTo, that must be handled differently.

Nevertheless, I'm puzzled because design patterns (GoF book) seem not consider this kind of situations.
What is the "real world" pattern that you would apply in this case?

Best Answer

I think the direction should be a Creational Pattern, page 33 in GoF book presents a help table for building a variable design. From the page:

Design Pattern         Aspect(s) That Can Vary
--------------         -----------------------
Abstract Factory (68)  families of product objects
Builder (75)           how a composite object gets created
Factory Method (83)    subclass of object that is instantiated
Prototype (91)         class of object that is instantiated

From this table, Prototype seems to fit the best it basically lets you to

specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

EDIT: nice detailed info here: http://sourcemaking.com/design_patterns/prototype

Please elaborate on your problem if this design is not enough...