I will give a simple example to help you understand my question. Suppose we have a rectangle and a Utility class with a method that creates a buffer arround a shape.
The .createBuffer
method has required and optional arguments:
-
required: radius
-
optional: direction (for example "inside" or "outside", default is "outside")
… maybe more arguments …
Every combination of arguments needs a different algorithm.
Which design pattern is appropriate for solving similar problems?
Best Answer
It's not clear to me that you need any design pattern -- at least not in the sense of the "Gang of Four" book.
From your description of the problem:
what you need is some way to get from input -> output where input is "combination of arguments" and output is "algorithm". This is essentially just a hash table (or a function), in which:
The second part of your problem -- "The .createBuffer method has required and optional arguments" -- isn't well-specified enough to give a sure answer, and will also depend on your choice of language. If your language supports optional arguments and default values, this problem nearly solves itself:
If you're in Java, you can use reference types and check for
null
, converting them to default values where necessary. Or even better, try this -- it helps clarify your intention to use nullable types to other programmers!As others mentioned, you could also throw the Builder pattern at it, but personally I wouldn't unless I was sure that I needed it, because a single method with a single type signature is simpler and easier to use.