share
Stack OverflowWhat design patterns do you use most often?
[+44] [52] DrFloyd5
[2008-09-08 15:45:35]
[ asp.net design-patterns ]
[ http://stackoverflow.com/questions/49974] [DELETED]

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.

For all for those is singleton most used pattern. Please read code.google.com/p/google-singleton-detector/wiki/…. - Jakub Šturc
in modern languages you use the most , iterator and collection patterns. as they are inert in the languages, and most problems needs iteration and memory management. - none
[+18] [2008-09-08 15:57:04] nsanders [ACCEPTED]

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.


(1) The Facade and Adapter patterns are the same...should just call them an Interface or Wrapper pattern or something. - omouse
(1) Adapter pattern: wrapping an existing object (Adaptee) with a new class (Adapter) that is to be used by an existing client. The Adaptee has a different interface than the client is expecting. Eg I might wrap a set of classes implementing a memory-based filesystem (Adaptee) with new classes that fit the interfaces used for regular files by a client. Facade pattern: wrap existing object with new interface that is easier to use than the existing interface. Eg writing a 'save' method that will open a file, write some data to it, and then close the file. I admit that the distinction is small. - Alex
1
[+13] [2008-09-17 18:53:09] Patrick Desjardins

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).


+1, those 2 are used in every day life so much. - Blindy
2
[+7] [2008-09-17 18:54:29] Guy Starbuck

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.


(2) I agree with you analysis. I think the patter I use the most is 'iterator'. - Kevin
(1) MVP is more of an architecture pattern than a design pattern. - Ricket
3
[+6] [2008-09-17 18:57:28] Ian Nelson

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

[1] http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

nice to know +1 - gpilotino
4
[+6] [2008-09-08 15:47:47] Chris Dail

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

  • Abstract Factory Pattern
  • Iterator Pattern
  • Observer Pattern
  • Singleton Pattern

5
[+6] [2008-09-08 15:51:47] Matt Dillard

Command Pattern [1]

[1] http://en.wikipedia.org/wiki/Command_pattern

6
[+5] [2008-09-08 15:53:38] Andy Whitfield

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


7
[+5] [2009-02-04 02:54:34] toshi

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.


8
[+4] [2008-12-09 09:51:56] g .

Iterator

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


9
[+4] [2008-09-16 07:18:01] superwiren

Am I the only one liking the Builder Pattern [1]?

:)

//W

[1] http://en.wikipedia.org/wiki/Builder_pattern

No, you are not :o) - Markus
10
[+3] [2008-09-17 18:55:37] Kirk Strauser

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.


11
[+3] [2008-09-17 18:56:19] paiNie

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

Factory methods are very useful ;)


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
12
[+2] [2008-09-17 18:54:00] Fossmo

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

[1] http://blog.fossmo.net/post/Model-View-Presenter-explained.aspx

13
[+2] [2008-09-15 17:09:46] JB King

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

Factory
Facade
Adapter
Strategy


14
[+2] [2009-09-14 17:28:35] Gabe Moothart

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 [1].

[1] http://www.berniecode.com/writing/inheritance/

15
[+1] [2008-09-21 15:59:29] community_owned

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.


(2) 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
16
[+1] [2009-09-14 16:55:30] amazedsaint

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


17
[+1] [2008-09-08 16:09:50] Philippe

State pattern is a good candidate.


18
[+1] [2008-09-08 15:51:54] Bill the Lizard

I use the Observer pattern [1] quite a bit.

[1] http://en.wikipedia.org/wiki/Observer_pattern

19
[+1] [2008-09-08 15:50:25] Quibblesome

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.


20
[+1] [2008-09-08 15:50:36] Matt Dillard

Singleton Pattern [1]

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

[1] http://en.wikipedia.org/wiki/Singleton_pattern

21
[+1] [2008-09-17 19:18:38] QBziZ

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.


22
[+1] [2008-09-21 15:48:45] David Robbins

The Command Pattern gives you great flexibility.


23
[+1] [2008-09-17 18:57:26] christopher_f

Dependency Injection, followed by Humble Dialog.


24
[+1] [2008-09-17 18:57:48] MikeZ

I find that I use the Decorator [1] 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.

[1] http://en.wikipedia.org/wiki/Decorator_pattern

25
[+1] [2008-09-17 18:59:21] Chris J

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

Singleton [1]

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

Facade [2]

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.

[1] http://en.wikipedia.org/wiki/Singleton_pattern
[2] http://en.wikipedia.org/wiki/Facade_pattern

26
[+1] [2008-09-17 18:59:44] dacracot

MVC by far.


27
[+1] [2008-09-17 19:01:15] Scott A. Lawrence

In my current assignment, template method [1] 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.

[1] http://en.wikipedia.org/wiki/Template_method_pattern

(1) I consider template method to be an antipattern, at least if you plan anything like continious improvement/refactoring. - krosenvold
28
[0] [2008-11-27 02:45:12] Samnang

Strategy Pattern [1] & Decorator Pattern [2]

[1] http://tech.wowkhmer.com/post/2008/11/14/Strategy-Design-Pattern.aspx
[2] http://en.wikipedia.org/wiki/Decorator_pattern

29
[0] [2010-09-28 21:11:26] Repo Man

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

30
[0] [2011-01-26 19:25:14] mike

Take a look also to GRASP patterns, it gives you a useful guidelines and principles to design better your application.


31
[0] [2008-12-12 20:34:31] Markus

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.


32
[-1] [2008-10-15 10:45:47] moogs

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


33
[-1] [2008-12-10 03:05:15] brady gaster

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.


34
[-1] [2008-12-12 17:14:26] Ola Eldøy

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

[1] http://en.wikipedia.org/wiki/Iterator_pattern

35
[-1] [2010-01-06 19:59:30] Gabe

Adding up the Design Patterns on here:

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

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

[1] http://www.dofactory.com/Patterns/Patterns.aspx

36
[-1] [2010-01-13 10:56:28] niao
  • Visitor
  • Singleton
  • Decorator
  • Template method
  • Composite

37
[-1] [2010-04-28 22:40:44] Adam Gent
  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.


38
[-1] [2008-12-09 09:21:05] Nicholas

Factory Pattern - Always program against an Interface :-)


39
[-1] [2008-12-09 09:33:32] dalle

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.


40
[-1] [2008-12-09 09:43:19] Codex

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.


41
[-1] [2008-09-21 15:57:38] Thorsten79
  • 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.


42
[-1] [2008-09-17 18:54:26] ddc0660

MVP and Singleton


43
[-1] [2008-09-17 19:14:48] Keith Rull

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


44
[-1] [2008-09-08 15:50:03] Marcio Aguiar

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


45
[-1] [2008-09-08 15:54:07] Rob Rolnick

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.


46
[-1] [2008-09-08 15:56:00] Anthony Mastrean

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 [1]' and ' yield [2]' documentation rather than 'Iterator' pattern information.

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

[1] http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx
[2] http://msdn.microsoft.com/en-us/library/9k7k7cf0%28VS.80%29.aspx
[3] http://www.google.com/search?q=site%3Ahttp%3A%2F%2Fblogs.msdn.com%2Foldnewthing+%22The+implementation+of+iterators+in+C%23+and+its+consequences%22

47
[-1] [2008-09-08 15:57:04] Tomas Pajonk

These are the big ones I usually use very often:

  • Strategy Pattern
  • Observer Pattern
  • Decorator Pattern

48
[-1] [2008-09-16 08:03:07] Johann Gerell

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_;
};

That's an Observer. - Roger Lipscombe
49
[-1] [2008-09-16 08:16:43] Roger Lipscombe

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.


50
[-1] [2008-09-16 08:24:52] ugasoft

in our company we prefer Resign Patterns [1]. 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.

[1] http://www.lsd.ic.unicamp.br/~oliva/fun/prog/resign-patterns

51
[-1] [2008-09-17 18:53:05] Mitchel Sellers

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


Yeah, I've been using singletons a lot at work to avoid creating global variables. - Rodrigo
@Rodrigo: I hope you're being sarcastic... - rcreswick
52