Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have been using this "design pattern" (may or may not be an "official" design pattern) for a while and I wanted to know if it had a name (so that I could name my classes after it).

Example in PHP code (though applies to any language) (the example is stupid please don't mind):

interface Formatter {
    public function format($variable);
}

class IntFormatter implements Formatter {
    public function format($variable) {
        echo (string) $variable;
    }
}

class StringFormatter implements Formatter {
    public function format($variable) {
        echo '"' . $variable . '"';
    }
}

Now the pattern I want to know if for this class:

class FormatterDispatcher implements Formatter {
    private $formatters = [];

    public function setFormatter($type, Formatter $formatter) {
        $this->formatters[$type] = $formatter;
    }

    public function format($variable) {
        $type = gettype($variable);

        return $this->formatters[$type]->format($variable);
    }
}

// Now in the code:
$formatter = new FormatterDispatcher();
$formatter->setFormatter('int', new IntFormatter());
$formatter->setFormatter('string', new StringFormatter());

$formatter->format($variable);

As you can see, it's just a proxy to other implementations of the interface. It will select the implementation to use based on the class of the parameter (here I used primitive types for simplicity's sake).

So what is the name of this pattern?

PS: in a language that supports Generics, the code would definitely look better, but I guess the spirit would be the same.

share|improve this question

closed as primarily opinion-based by MichaelT, Bart van Ingen Schenau, JeffO, Jimmy Hoffa, gnat Jun 19 at 4:07

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

    
Only as a comment, Why your types (own classes) doesn't implements Formatter?. –  Arnaldo Ignacio Gaspar Véjar Jun 18 at 13:51
    
@ArnaldoIgnacioGasparVéjar I did a typo in my example, I had the VariableFormatter interface, I changed it to Formatter. Does that answer your question? –  Matthieu Napoli Jun 18 at 13:52
    
Close-votes: please explain how it is opinion based? I am asking for the name of this design pattern. –  Matthieu Napoli Jun 18 at 13:54
    
I think that the pattern is innecessary if you are only holding formats for custom classes. Your classes should only implement the format() method as toString(). –  Arnaldo Ignacio Gaspar Véjar Jun 18 at 14:02
1  
This question appears to be off-topic because it is just asking for the name of something. –  JeffO Jun 18 at 19:12

4 Answers 4

up vote 2 down vote accepted

Looks like a variation on Strategy, where the twist is you're looking up the strategy for a type in a hash keyed by the type.

It's also "dynamic dispatch", which is fundamental mechanism in OO. That's where you decide which method to execute at runtime based on the type of an object.

In an OO language like Java, it's usually an anti-pattern to base logic on a instance's type -- it weakens the proposition of OO. Using "if instanceof" or "switch o.getClass()" is manually replicating logic that the language does for you (!) So usually you're supposed to use polymorphism or extention, method overloading, or look at a wrapper or Decorator to do this sort of thing. All of those are run-time logic based on type. Or you could hide the map of type formatters in a Factory class that produces the specific formatter, and makes the decision based on type (which is kind of the function of a factory).

But that's sort of a purist approach. This is nice straightforward code that saves a bunch of lines of code. ...But if you write it in Java, you're kind of asking to write a bunch of lines of code anyway. ;)

share|improve this answer
    
Now that you mention it I remember how in Java instanceof and the likes are considered anti-pattern. But honestly I don't see how to do differently. Method overloading would mean putting format() in the objects themselves, which is bad for separation of concern. You said hide the map of type formatters in a Factory class but in the end it's just the same (it's just "hidden" in a factory ;). And to use Decorators, I would also have to use some kind of instanceof or switch o.getClass() somewhere anyway when decorating the objects (based on their classes). –  Matthieu Napoli Jun 18 at 14:22
    
1) Ideally, you'd put the format command in the classes themselves, like integer.format() and string.format(). Obviously, you can't do that, so you'd think about using the Decorator pattern to extend a class you can't otherwise extend. ;) 2) Method overloading is probably the offcial way do do it, since format(Integer i) and format(String s) is really just a map of functions based on type ;) but it doesn't seem as flexible as writing formatting Strategy classes. –  Rob Y Jun 18 at 14:30
    
Yeah I want to leave the possibility open for other implementations, so that users (of the library) can both add new objects and their formatters. –  Matthieu Napoli Jun 18 at 14:32
    
3) Sometimes in OO hiding the "off" code helps keep the OO Police off your back. In this case, you might be able to beat the heat by saying your FomatterDispatcher is itself a factory. But putting "Dispatcher" in the name signals you're taking over Dynamic Dispatch from the language. Mind you, I think this is a nice simple approach, I just wanted to provide a complete answer. –  Rob Y Jun 18 at 14:32
1  
Unfortunately PHP doesn't do dynamic dispatching in the form of method overloading. It does appear to be common to mimic it in PHP with a combination Strategy/Observer pattern. –  Steve Buzonas Jun 28 at 10:47

This is not Factory - Factory would return a Formatter for you to use.

This looks more like Multiple Dispatch. It's classified as a language feature rather than as a design pattern, but I find the main difference between language features and design patterns is if it's support directly by the language's syntax or standard library

share|improve this answer
    
That's very interesting. Would Double Dispatch be even closer? –  Matthieu Napoli Jun 18 at 14:14
    
@MatthieuNapoli Maybe, but since you want it mainly for naming your classes, adding "Double"(or "Multiple") will only confuse the class names - "Dispach" is enough. –  Idan Arye Jun 18 at 14:19
    
You are right, Dispatch is enough for the code :) –  Matthieu Napoli Jun 18 at 14:23

At first I thought you might be using the Factory Method Pattern but you're creating your instances up front and not dynamically. Instead you're dynamically dispatching strategies. So I guess you have the Strategy Pattern but there's something else I'm not identifying.

share|improve this answer
1  
Yes I thought about the strategy pattern at first too, but usually in that pattern there is only 1 strategy chosen at runtime, whereas here there are several and a "switch" is made based on the object type. –  Matthieu Napoli Jun 18 at 14:24

Looks like interpreter pattern to me. You are trying to interpret by chaining the formatters.

http://en.m.wikipedia.org/wiki/Interpreter_pattern

share|improve this answer
1  
The interpreter pattern is more classically associated with a domain specific language within the program. I don't see any examples of a DSL within the example given. Chaining (a fluent interface) doesn't imply an interpreter. –  MichaelT Jun 18 at 19:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.