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'm trying to educate my colleagues in the area of design patterns. Some of the original Gang of Four patterns are a little esoteric, so I'm wondering if there is a sub-group of "essential" patterns that all programmers should know. As I look through the list, I think I've probably used -

  • Abstract Factory
  • Factory Method
  • Singleton
  • Bridge
  • Facade
  • Command

Which ones do you actually use in practice, and what do you use them for?

Link for those wanting a list of patterns

share|improve this question

closed as not constructive by Jarrod Roberson, Thomas Owens Feb 13 '12 at 18:31

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

7  
IMHO, the question is too vague to yield useful discussion. Do you want one answer per pattern or one answer per combination of patterns? –  Macke Feb 17 '11 at 22:24
    
Some reasons why you use these patterns would be useful, otherwise you're just listing concepts... Imagine asking the question: "What keywords do you use?" and gathering lists of "for, if, while... etc" - difficult to measure just how pointless that would be. –  Slomojo Feb 17 '11 at 22:39
1  
I disagree Slomojo - I think it would be quite handy to know whichi keywords were commonly used and which were not in a language. Same goes for base classes, for example. –  Craig Schwarze Feb 17 '11 at 22:46
1  
Modified it a fair bit more - hopefully this will generate some better discussion now. –  Craig Schwarze Feb 18 '11 at 0:28
1  
Which kinds of fruit do you actually eat? I'm curious to know what you are hoping to get out of this question. If you see a pattern that 3 or 4 people have used but you haven't, is that going to make you use it? –  Marcie Feb 18 '11 at 15:23

10 Answers 10

up vote 4 down vote accepted

Here's a list of which ones I've used or seen in practice:

Singleton - Application object in ASP.Net being a prime example of this.

Adapter - Connecting to databases usually can involve an Adapter class at least in my area of .Net stuff.

Factory - General for generating objects though I saw this more in some older classic ASP back in the day.

Strategy - I had an application which for each type of device I had a similar structure for the class that I'd consider an implementation of this pattern.

Facade - In some ways this is similar to the Adapter pattern in terms of being something that ties together a couple of systems usually.

share|improve this answer
1  
All valid uses. For anyone also reading this - keep in mind that these patterns are certainly not limited to these. –  Boris Yankov Jul 20 '11 at 20:32

The authors compiled the patterns from observed designs they found in real applications. No one person will likely use all of them, but they are all used.

share|improve this answer
    
Which has you used smithco, and what for? –  Craig Schwarze Feb 18 '11 at 0:28
    
@CraigS I've used many of them. The authors of Design Patterns have a set of good examples with each pattern they describe. The best suggest I can give is to spend the time to read the book thoroughly. –  smithco Feb 18 '11 at 0:57

Decorator.

EDIT: In almost every project that gets beyond the 'trivial' stage, one ends up with an IAction interface (details may differ):

// Programming Language does not matter
interface IAction {
     bool operateOn(Foo* target);
     string getDisplayName(); // useful for debugging and logging
};

The next hour I spend on writing a lot of small, almost trivial classes that implement IAction. When combined, they are very powerful and flexible.

E.g. an LogAction (write to log and perform the IAction), NullAction (do nothing and return true), ActionList (perform a list of IActions, and return the ANDing of the bools). In some cases an AndAction (return the AND-ing of two actions, could be short-circuited or not), OrAction, NotAction make sense as well.

Although technically from the examples above only the LogAction is a Decorator (the other do not operate on exactly 1 IAction), I still consider this a generalization of the Decorator pattern when I make a ActionList of LogActions of IActions.

share|improve this answer
    
What do you use it for? –  Craig Schwarze Feb 18 '11 at 0:22
1  
@CraigS Example added on request. –  Sjoerd Feb 18 '11 at 17:14
    
It looks more like a mix of Decorator and Composite actually, which is fine, and a perfect demonstration that the difficulty in patterns does not come from using them independently, but from mixing them together :) –  Matthieu M. Feb 18 '11 at 18:34
    
A yes, this is a classic. It is Composite pared with command. There is actually a name for this patten: it's called "Specification" (en.wikipedia.org/wiki/Specification_pattern). –  Martin Wickman Mar 20 '11 at 23:09

I assume you mean to restrict the question to usage of patterns in own code / projects (no class libraries and 3rd party frameworks).

As did others, I have also used the Factory patterns most often. Then

  • Singleton: not so much nowadays, but still sometimes it is necessary, typically for global configuration data
  • Strategy and Template Method: quite often, e.g. for representing different kinds of calculations in our app
  • Builder: for marshalling the results of transactions with a mainframe system into output objects (in some cases it includes a great deal of text parsing and creating large object hierarchies)
  • Command: I implemented it only once many years ago, but nowadays in our Java project I use Callables every now and then, which I believe are basically Commands
share|improve this answer

Well if you use common libraries like ACE, you end up using more than you think you use. I use Observer/Observable extensively :-)

share|improve this answer

I used a Builder at least once (the same converter process could build HTML or Excel output).

I frequently use the Template Method (for JDBC-related tasks, or abstract Swing controllers).

Once I had to develop lots of new features into a form-based application, which was a mess. I could only progress after I had refactored the existing stuff to a State-pattern based solution. (Well, most of it).

I also use Commands frequently (Swing Actions), and Observers too.

Once I used a Mememento-like solution for detecting changes in Swing forms. The form would serialize its state what I compared (equals()) to earlier states.

share|improve this answer

I believe I have most them thru-out my career. the only one I am sure I have not used is that Adapter Pattern that is implemented with multiple inheritance on the book as I am not a big fan of multiple inheritance.

share|improve this answer

I've used many of the others which have already been mentioned (Singleton, Factory, Builder, Command, Strategy, etc...)

One I haven't seen mentioned yet is Flyweight, which I tend to use a lot. I've provided an example implementation below:

/**
 * Flyweight class representing OCR digits.
 * 
 * @author matt
 *
 */
public class Digit {
    /** Static flyweight map containing Digits which have been encountered. **/
    private static Map digits = new HashMap();

    /** The block of text representing Digit. **/
    private String blockRep = null;

    /** A map representing acceptable blocks of characters and the string representation of their
     * numerical equivalents.
     */
    public static final Map VALID_DIGITS;

    /** Enum of valid digits. **/
    public static enum DigitRep {
        ZERO    (   " _ \n" +
                    "| |\n" +
                    "|_|"       ),

        ONE (       "   \n" +
                    "  |\n" +
                    "  |"       ),

        TWO (       " _ \n" +
                    " _|\n" +
                    "|_ "       ),

        THREE   (   " _ \n" +
                    " _|\n" +
                    " _|"       ),

        FOUR    (   "   \n" +
                    "|_|\n" +
                    "  |"       ),

        FIVE    (   " _ \n" +
                    "|_ \n" +
                    " _|"       ),

        SIX     (   " _ \n" +
                    "|_ \n" +
                    "|_|"       ),

        SEVEN   (   " _ \n" +
                    "  |\n" +
                    "  |"       ),

        EIGHT   (   " _ \n" +
                    "|_|\n" +
                    "|_|"       ),

        NINE    (   " _ \n" +
                    "|_|\n" +
                    " _|"       );

        private String blockRep;

        DigitRep(String blockRep) {
            this.blockRep = blockRep;
        }

        @Override
        public String toString() {
            return blockRep;
        }
    }

    static {
        /* Initialize the map of acceptable character blocks. */
        Map tmpMap = new HashMap();
        tmpMap.put( DigitRep.ZERO.toString(),   "0");
        tmpMap.put( DigitRep.ONE.toString(),    "1");
        tmpMap.put( DigitRep.TWO.toString(),    "2");
        tmpMap.put( DigitRep.THREE.toString(),  "3");
        tmpMap.put( DigitRep.FOUR.toString(),   "4");
        tmpMap.put( DigitRep.FIVE.toString(),   "5");
        tmpMap.put( DigitRep.SIX.toString(),    "6");
        tmpMap.put( DigitRep.SEVEN.toString(),  "7");
        tmpMap.put( DigitRep.EIGHT.toString(),  "8");
        tmpMap.put( DigitRep.NINE.toString(),   "9");       
        VALID_DIGITS = Collections.unmodifiableMap(tmpMap);
    }

    /**
     * Private constructor to enforce flyweight/factory pattern.
     * 
     * @param blockRep
     */
    private Digit(String blockRep) {
        this.blockRep = blockRep;
    }

    /**
     * Flyweight factory method to create a Digit object from the "block"
     * representation of the digit.
     * @param blockRep The "block" representation of a digit.  Should look
     * something like:
     * " _ \n"
     * "|_|\n"
     * "|_|"
     * @return A flyweight Digit object representing the digit.
     */
    public static synchronized Digit getDigit(String blockRep) {
        Digit digit = digits.get(blockRep);
        if(digit == null) {
            digit = new Digit(blockRep);
            digits.put(blockRep, digit);
        }

        return digit;
    }

    /**
     * Determines whether or not the digit is valid.
     * @return true if the digit is valid, else false.
     */
    public boolean isValid() {
        return VALID_DIGITS.containsKey(blockRep);
    }

    /**
     * Accessor method to get the block representation of this digit.
     * 
     * @return
     */
    public String getBlockRep() {
        return blockRep;
    }

    @Override
    public String toString() {
        return VALID_DIGITS.containsKey(blockRep) ? VALID_DIGITS.get(blockRep) : "?";
    }
}
share|improve this answer
1  
+1 one of the lesser known but still incredibly useful patterns. –  MattDavey Aug 21 '12 at 13:48

I'm fond of Decorator. The only one I've got add to those mentioned is Proxy.

share|improve this answer

Most of the original Gang of Four patterns are still used today, but there are other now popular ones that aren't in the book.

Find a reference for Design Patters in the language you use. They tend to be more concrete and use specific language features to implement the patterns in a more succinct and elegant way.

Three great resources for Design Patterns:

"Head First Design Patterns" Book - the language of choice is Java, but is relevant to all languages. dofactory Design Patterns - great and free .net design patterns explanations with code. PluralSight - Design Patterns Library - this one is paid, but is too good not to include it in the list.

share|improve this answer

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