views:

2261

answers:

52

As a relative newcomer to the concept of design patterns, what are some of the most frequently used patterns?

This will help me focus my studies to patterns that may be relevant to the largest number of issues.

+4  A: 

These are the big ones I typically use all the time:

  • Abstract Factory Pattern
  • Iterator Pattern
  • Observer Pattern
  • Singleton Pattern
Chris Dail
A: 

Complementing @Chris answer, the Decorator and Strategy patterns are very useful in most applications too.

Marcio Aguiar
+1  A: 

That said I find decorator to be a useful one because often I want to add optional functionality without modifying the underlying architecture. The factory pattern is another one that crops up all over the place although in a lot of cases it is implicit as opposed to actually being called "factory" that happens to the observer a lot as well.

The one I see the most is definately the one that I shouldn't be used so liberally and that is the Singleton.

Quibblesome
+1  A: 

Singleton Pattern

(Answering one-per-post to facilitate voting on individual patterns)

Matt Dillard
+4  A: 

Command Pattern

Matt Dillard
+1  A: 

I use the Observer pattern quite a bit.

Bill the Lizard
+5  A: 

Inversion Of Control and Dependency Injection. Understand these and used correctly, can start to make your code more maintainable and testable.

Andy Whitfield
A: 

In school, I find that strategy design pattern to be useful. It lets me do multiple implementations of a design, and then dynamically change between them at runtime.

It was particularly handy when testing various branch prediction algorithms for my Comp Architecture course.

Rob Rolnick
A: 

In C#, the 'Iterator' pattern is implemented in the 'foreach' loop (and other general uses of 'IEnumerable'). So, if you are studying for the purpose of writing ASP.NET applications (assumed from the tag you applied), I would suggest reading the 'IEnumerable' and 'yeild' documentation rather than 'Iterator' pattern information.

Also see Raymond Chen's series on iterators in C#.

Anthony Mastrean
+13  A: 

For studying, I still like the original GoF Design Patterns book. (Some people prefer the more friendly prose books like Head First Design Patterns).

Here's how I've used a few of the patterns lately:

Abstract Factory

Inside our ray tracer, our factory produces one type of objects. Inside our QT-based (graphical) scene editing tool, it produces auxiliary data in another data structure.

Facade

Produced a simple programmatic interface for talking to some of our existing code using unix pipes. (There was an existing interface/protocol for this communication).

Adapter

I wrote some simple wrapper code to take a library in C (for geodetic transforms) and integrate it to our existing C++ code.

Composite

Used in the heart of our ray tracer. Both geometry lists and end types like facetized geometry, solid boxes, solid spheres, etc derive from a Geometry class. A geometry list can hold any Geometry-derived type, including other geometry lists. This reproduces the hierarchy of our scene input files and allows for various memory/speed optimizations.

nsanders
The Facade and Adapter patterns are the same...should just call them an Interface or Wrapper pattern or something.
omouse
A: 

These are the big ones I usually use very often:

  • Strategy Pattern
  • Observer Pattern
  • Decorator Pattern
Tomas Pajonk
+1  A: 

State pattern is a good candidate.

Philippe
+2  A: 

Just to add another opinion, here's my list:

Factory
Facade
Adapter
Strategy

JB King
+3  A: 

Am I the only one liking the Builder Pattern?

:)

//W

superwiren
No, you are not :o)
Markus
A: 

I find myself returning to variants of Factory and Visitor on a regular basis, but the pattern I use most often has no name that I'm aware of. It's probably also a variant of some well known pattern, like Callback or so. It's kind of a poor man's (read: C++ developer) event handler (as in .Net) replacement, for decoupled communication between two objects.

This is basically it's essence, somewhat contrived:

class TrackPlayer;

//
// Callback interface.
//
struct TrackPlayerEventHandler
{
    virtual void OnStarted(TrackPlayer& player) = 0;
    virtual void OnFinished(TrackPlayer& player) = 0;

protected:
    virtual ~ TrackPlayerEventHandler() { }
};

//
// Client.
//
class TrackPlayer
{
public:
    TrackPlayer(TrackPlayerEventHandler& eventHandler)
    : eventHandler_(eventHandler)
    {
    }

    void Play()
    {
        AsyncPlay();
        eventHandler_.OnStarted(*this);
        WaitAndPumpMessagesUntilFinished();
        eventHandler_.OnFinished(*this);
    }

protected:
    TrackPlayerEventHandler& eventHandler_;
};

//
// Host.
//
class Jukebox : private TrackPlayerEventHandler
{
public:
    Jukebox()
    : player_(*this)
    {
    }

    void Play()
    {
        player_.Play();
    }

private:
    //
    // TrackPlayerEventHandler implementations.
    //
    void OnStarted(TrackPlayer&)
    {
        bellsAndWhistles_.Activate();
    }

    void OnFinished(TrackPlayer&)
    {
        bellsAndWhistles_.Deactivate();
    }

    TrackPlayer player_;
    BellsAndWhistles bellsAndWhistles_;
};
Johann Gerell
That's an Observer.
Roger Lipscombe
A: 

In C++, on Windows, I often use a combination of the Observer, Proxy and Command patterns for cross-thread marshalling.

Some more detail: In Win32, windows have thread affinity. This means that you shouldn't really call them (via SendMessage) from a different thread than the thread that created the window. SendMessage will block until the UI thread returns, which can (if you're not careful) lead to deadlocks.

So, I generally have the background thread take an Observer interface. I pass it a Proxy implementation of the Observer, which uses PostMessage (usually via a hidden window) to marshal the relevant information to the UI thread. To avoid having to marshal/unmarshal the parameters by hand, I pass Command objects from the background thread to the UI thread (by putting them in the lParam parameter to PostMessage). The Command objects take a C++ pointer-to-member-function parameter, and the list of parameters to that function. Then, when the UI thread calls Execute, they simply call the real Observer.

I wrote this technique up on my website: http://www.differentpla.net/content/2004/06/using-the-observer-proxy-and-command-patterns-to-marshal-progress-reporting-from-a-background-thread

More recently, I've been looking at using a std::tr1::function to package up the parameters. This is, effectively, an implementation of the Command pattern.

Roger Lipscombe
A: 

in our company we prefer Resign Patterns. I'm joking, obviously. You should read the GOF book and think about design patterns. After that, you should read some criticism to design patterns, as the realtimecollisiondetection blog or futurist programming theory (I'll find some more link and I'll add to this post) and just looking at this contrast you can make an unbiased opinion about them.

ugasoft
A: 

For data access components, as well as logging systems I find myself using the singleton pattern quite freqently

Mitchel Sellers
Yeah, I've been using singletons a lot at work to avoid creating global variables.
Rodrigo
@Rodrigo: I hope you're being sarcastic...
rcreswick
+12  A: 

Decorator : to change an object without affecting the original one.

Observer : To have an indetermined object to be fired in some event. (Really like the way C# does it with Event and Delegate).

Daok
+1, those 2 are used in every day life so much.
Blindy
+2  A: 

I use Model-View-Presenter and Dependency Injection a lot. More information about MVP can be found here at this link.

Fossmo
A: 

Singleton is my favorite design pattern and MVC pattern is most used one.

amadamala
A: 

MVP and Singleton

ddc0660
+6  A: 

With design patterns, the trick is that you use a lot of them without even being aware.

As a Microsoft developer, I use the "observer" or "publish/subscribe" patterns a lot just because the tools implement it frequently, with the event/delegate/event handler code generation in Winforms, WPF and ASP.NET.

As far as deliberately applied patterns, MVP is probably the one that I think about and use the most.

Guy Starbuck
I agree with you analysis. I think the patter I *use* the most is 'iterator'.
Kevin
MVP is more of an architecture pattern than a design pattern.
Ricket
+3  A: 

MVC, by a wide margin. My company is in the process of porting all our business logic to one standard backend and re-writing our applications as lightweight frontends. It takes some planning, but it's worth it when you discover you can make a nice web interface to a fairly complex system in a day or two.

Just Some Guy
+3  A: 

Most of cases singleton is used, it is antipattern (say "Hello" to unit tests)

Factory methods are very useful ;)

paiNie
I couldn't agree more! (first part)At first glance, Singleton seems like an awesome idea... But it breaks fundamental ideas of object-oriented programming and leads to tons of virtual references to the singleton object all over the place, resulting in hard-to-debug code.Yuck!
Ricket
+1  A: 

Dependency Injection, followed by Humble Dialog.

christopher_f
+5  A: 

I find myself using Chain Of Responsibility quite often. It's a good way of decoupling classes and developing flexible systems.

Ian Nelson
nice to know +1
gpilotino
+1  A: 

I find that I use the Decorator pattern quite a bit in protocol-type objects to split the actual protocol level processing from the communications medium that carries the protocol.

For example, I recently used Decorator to split the LPD (Line Printer Daemon) and POP3 (Post Office Protocol, version 3) protocols from the TCP sockets that carried the data, and found that the decoupling made each of the solutions MUCH easier to unit test and develop.

MikeZ
+1  A: 

Singleton and Facade tend to find their way into my coding a lot.

Singleton

Singleton has become so possibly overused though that it really isn't a specific pattern anymore.

Facade

Facade has become more useful to me depending on whether or not I am attempting to use multiple external libraries. Very often I find that they are far more complicated than I need and find it easier to program the lightweight interface that either assumes many of the inputs or directives, or even method calls if I do the same process of method calls repeatedly than typing it out in my code a lot. And with modern code inlining, most of the function call overhead is often removed anyways.

I'd say those are the two I use the most at least.

Chris J
+1  A: 

MVC by far.

dacracot
+1  A: 

In my current assignment, template method gets used quite a bit. We tend to use it to guarantee the order that certain methods are executed in, while leaving the implementation of the individual steps to be customized by developers later.

Scott A. Lawrence
I consider template method to be an antipattern, at least if you plan anything like continious improvement/refactoring.
krosenvold
A: 

Monostate for database connection. Factory for my objects. Strategy for decision making on which object to create

Keith Rull
+1  A: 

Strategy.

I feel that once you have a clear interface/implementation separation, patterns become almost implicit. To the point that Strategy, Decorator, Factory, Chain of command, ... almost blend into each other.

QBziZ
+1  A: 

The Command Pattern gives you great flexibility.

David Robbins
A: 
  • MVC pattern because it is inevitable whenever dynamic data is shared in an application.
  • Facade pattern because it makes complicated things easier to someone using your code (and yourself).
  • Singleton pattern for all elements in an application that can't be shared.

And probably several others which I simply implement without realizing that I'm just using a pattern.

Thorsten79
+1  A: 

I tend to use Global Variables (erm, Singleton) extensively because I've never been able to find a good place to put my Factories, Abstract Factories, and it also means I can store objects that allow my Observables to register with Observers without needing to pass around objects.

Many applications can be written so that most of your methods actually only have 0-1 parameter this way! Doing this has shortened my unit tests a lot, since there are fewer cases to check (less params, less options). It does take a bit of effort to set up the system so the tests will actually run (vs. lots of NullPointerExceptions...) but that only takes 300-500 lines in a SetUp method.

Man I really have to disagree with this sort of pattern. I have seen this done and you end up with a spider web of dependencies and classes that have hundreds of collaborators with very little cohesion.
Adam Gent
A: 

Strategy. Because I have several spec change requests per week. Gah!

moogs
+1  A: 

Strategy Pattern & Decorator Pattern

Samnang
A: 

Factory Pattern - Always program against an Interface :-)

Nicholas
A: 

Visitor

In private: I always like to travel to new places.

In code: To separate algorithms from the object structure upon which it operates.

Observer

In private: I like to see new stuff.

In code: For automatic notifications, and loose connection between objects.

dalle
A: 

During my experience of programming server-side components I have the following patterns to be useful:

1] Factory Patterns - They are great for seperating the creation logic from the usage of the object itself. Especially useful when creation of objects requires passing thro' complex and common object-creation logic and authentication rules

2] Singleton - Almost all projects required this one to be used. The common components that required this were the Logger, the ErrorHandler, the BusinessBroker etc.

Codex
+4  A: 

Iterator

It isn't the most glamorous design pattern, but it is by far the one I use most often.

g .
A: 

Without fail, the Decorator pattern. I'm not sure why but it always seems to come up as a need in my architectures. Of course, Repository designs and most recently the MVC approach have become significant in my development paradigm, but Decorator is one that always seems to be needed.

brady gaster
A: 

The Iterator pattern is a simple, yet powerful way to loop through all kinds of collections. (Arrays, data sets, files... you name it!)

Ola Eldøy
+1  A: 

Decorator pattern, and I also use the Visitor pattern quite often. Of course, there are more complex use cases, but a Visitor is handy for many enum types. It becomes even more flexible if you use generics for return value and and exceptions. In most cases, I define an enum (in Java) as:

enum Language {
   ENGLISH { 
       <R, E extends Exception> R accept(Visitor<R,E> visitor) throws E {
           return visitor.visitEnglish(this);
       }
   },
   GERMAN { 
       <R, E extends Exception> R accept(Visitor<R,E> visitor) throws E {
           return visitor.visitGerman(this);
       }
   };
   abstract <R, E extends Exception> R accept(Visitor<R,E> visitor) throws E;

   public static interface Visitor<R,E extends Exception> {
       public R visitEnglish(Language l) throws E;
       public R visitGerman(Language l) throws E;
   }
}
public class GreetingVisitor implements Language.Visitor<String, RuntimeException> {
    public static final GreetingVisitor INSTANCE = new GreetingVisitor();
    public String visitEnglish(Language l) { return "Hello"; }
    public String visitGerman(Language l) { return "Guten Tag"; }

    //Example usage:
    public static String greet(Language language) {
        return language.accept(GreetingVisitor.INSTANCE);
    }
}

That visitor can be used like a switch statement (often as anonymous classes), but with one main difference: if you add support for another language (add it to the enum values, add another visitor method), the compiler finds all visitor implementions where you must add support for your new language. If you used a simple switch statement, you would easily miss one occurence.

Markus
+5  A: 

Strategy Pattern

This pattern is useful when I want to minimamize the modification to the existing code upon introducing/changing new features. The use of polymorphism is more maintainable than the use of branching but we have to be careful not to abuse this pattern because of the performance overhead and increased code complication. We must use the pattern at the extention/evolution points where there is absolutely a benefit.

Template Method Pattern

This pattern is useful to implement an application framework to limit the freedom of programmers in order to produce homogeneous code from a bunch of developers. It enforce developers to implement the business logic in the same structure as other developers. It helps making the code more maintainable.

toshi
+1  A: 

I'm not really sure whether your question is specific to GOF patterns or regarding all - including Enterprise application related patterns.

There is no silver bullet - It depends on the design problem you are trying to solve, and hence some what related to the domain you are working.

Normally the thought process is like

  • How you identify the entities in your system,
  • How you identify the design problems, and
  • How you apply patterns to address your design specifications.

Again, the frameworks/platforms you use for development may have already implemented patterns as part of their architecture - so you'll be using them anyway.

For me, the most common ones are observer, decorator, singleton, chain of responsibility and facade.

You might want to go through this article on "Applying Design Patterns" - http://amazedsaint.blogspot.com/2009/06/software-design-patterns-for-everyone.html

amazedsaint
+2  A: 

More important than any pattern is the Gang of Four advice to favor composition over inheritance. What you want is a lot of small, single-responsibility objects that can be composed together in different ways instead of a monolithic class hierarchy. This principle is at the core of most GOF patterns.

A good (if overstated) discussion of inheritance vs. composition is here.

Gabe Moothart
A: 

Adding up the Design Patterns on here:

  • Factory x6
  • Observer x5
  • Strategy x4
  • Decorator x4

DoFactory also tells you the frequency of use for each Design Pattern.

Gabe
A: 
  • Visitor
  • Singleton
  • Decorator
  • Template method
  • Composite
niao
A: 
  1. Iterator
  2. Adapter
  3. Decorator

However... I have been finding myself using the Visitor pattern to mimic a more powerful switch statement / pattern matching with out the instanceof and or casting. Obviously it would be nice if I had multiple dispatch like CLOS or pattern matching like Haskell, Scala or ML but this is a good substitute

public interface ObjectTypeToMatchOn {
    public void accept(SomeTypeOfVisitor v);
}
public class Stuff implements ObjectTypeToMatchOn {
   public void accept(SomeTypeOfVisitor v) { v.visit(this); }
}

public class AnotherClassIWantToMatchOn implements ObjectTypeToMatchOn {
   public void accept(SomeTypeOfVisitor v) { v.visit(this);
}

public interface SomeTypeOfVisitor {
   public void visit(Stuff s);
   public void visit(AnotherClassIWantToMatchOn a);
}

// Now Here comes the Switch/ Pattern Match

public void doStuff(AbstractStuff s) {
    s.accept(new SomeTypeOfVisitor() {
     // Implement each of the visits instead of
     // each case statements you implement the methods. 
    });
}

If you want to walk through a collection of ObjectTypeToMatchOn and do different things you would have to do a bunch of

if (o instanceof Stuff) {
}
else if ( o instanceof AnotherClassIWantToMatchOn) {
}

If you add another type that you want to switch on you will have remember to go to all the code that does this kind of if/else and add another if/else for the new type.

Yeah you could use polymorphic methods on your hierarchy but you can really implement one type of pattern match if you do that.

Adam Gent
+1  A: 

If you conducted a survey of computer programmers using standard OOP languages you'd probably find that the most important patterns are the following, in order:

  1. Iterator (which is why it is implemented as a built-in language feature of C#)
  2. Decorator / Adapter
  3. Observer (also a built-in feature)
  4. Composite / Visitor
  5. Builder (implemented gratuitously in various BCL classes)
  6. Proxy (also implemented gratuitously in BCL classes)
  7. Factory method
  8. Template method
Repo Man