views:

2616

answers:

12

Hi everyone, I'm reading through head first design patterns at the moment and while the book is excellent I also would like to see how these are actually used in the real world.

If you know of a good example of design pattern usage (preferably in a OSS program so we can have a look :) then please list it below.

+1  A: 

What particular patterns are you interested in? Most of the well written code online uses one or more patterns.

Kaius
+2  A: 

An ah-ha moment for me for the observer pattern was to realize how closely associated it is with events. Consider a Windows program that needs to acheive loosely communications between two forms. That can easily be accomplished with the observer pattern.

The code below shows how Form2 fires an event and any other class registered as an observer get its data.

See this link for a great patterns resource: http://sourcemaking.com/design-patterns-and-tips

Form1's code:

namespace PublishSubscribe
{
    public partial class Form1 : Form
    {
        Form2 f2 = new Form2();

        public Form1()
        {
            InitializeComponent();

            f2.PublishData += new PublishDataEventHander( DataReceived );
            f2.Show();
        }

        private void DataReceived( object sender, Form2EventArgs e )
        {
            MessageBox.Show( e.OtherData );            
        }
    }
}

Form2's code

namespace PublishSubscribe
{

    public delegate void PublishDataEventHander( object sender, Form2EventArgs e );

    public partial class Form2 : Form
    {
        public event PublishDataEventHander PublishData;

        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click( object sender, EventArgs e )
        {
            PublishData( this, new Form2EventArgs( "data from form2" ) );    
        }
    }

    public class Form2EventArgs : System.EventArgs
    {
        public string OtherData;

        public Form2EventArgs( string OtherData )        
        {
            this.OtherData = OtherData;
        }
    }
}
rp
where is the PublishData event written?
Anirudh Goel
I mean the PublishDataEventHander, what should happen in that event where is that written?
Anirudh Goel
A: 

This question is too subjective for StackOverflow, as per the FAQ

What kind of questions should I not ask here?

Avoid asking questions that are subjective, argumentative, or require extended discussion. This is a place for questions that can be answered!

May I suggest you check out a list of common design patterns, and if interested, ask more on them in detail? (in their own questions of course) this helps keep the content focused..

Thanks :)

Rob Cooper
+3  A: 

I use passive view, a flavor of the Model View Presenter pattern, with any web forms like development (.NET) to increase testability/maintainability/etc

For example, your code-behind file might look something like this

Partial Public Class _Default
    Inherits System.Web.UI.Page
    Implements IProductView

    Private presenter As ProductPresenter

    Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
        MyBase.OnInit(e)
        presenter = New ProductPresenter(Me)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        presenter.OnViewLoad()
    End Sub

    Private ReadOnly Property PageIsPostBack() As Boolean Implements IProductView.PageIsPostBack
        Get
            Return Page.IsPostBack
        End Get
    End Property

    Public Property Products() As System.Collections.Generic.List(Of Product) Implements Library.IProductView.Products
        Get
            Return DirectCast(gridProducts.DataSource(), List(Of Product))
        End Get
        Set(ByVal value As System.Collections.Generic.List(Of Product))
            gridProducts.DataSource = value
            gridProducts.DataBind()
        End Set
    End Property
End Class

This code behind is acting as a very thin view with zero logic. This logic is instead pushed into a presenter class that can be unit tested.

Public Class ProductPresenter
    Private mView As IProductView
    Private mProductService As IProductService

    Public Sub New(ByVal View As IProductView)
        Me.New(View, New ProductService())
    End Sub

    Public Sub New(ByVal View As IProductView, ByVal ProductService As IProductService)
        mView = View
        mProductService = ProductService
    End Sub

    Public Sub OnViewLoad()
        If mView.PageIsPostBack = False Then
            PopulateProductsList()
        End If
    End Sub

    Public Sub PopulateProductsList()
        Try
            Dim ProductList As List(Of Product) = mProductService.GetProducts()
            mView.Products = ProductList
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
End Class
Toran Billups
+2  A: 

Use code.google.com

For example the search result for "Factory" will get you a lot of cases where the factory Pattern is implemented.

Maximilian
+1  A: 

The Chain of Command pattern is implemented in the handling of DOM events. For example, (and simplifying slightly) when an element is clicked on, that element gets the first opportunity to handle the event, and then each ancestor in tern until the top level document is reached or one of them explicity stops the event "bubbling" any further.

Nick Higgs
+1  A: 

C#, Java and Python have a standard implementation of the Iterator pattern. In C# and Python this has been intergrated in the language so you can just use yield return statements.

Mendelt
A: 

Composite is used extensively in UI. Components can be leaf components e.g. buttons and labels or composites e.g. panels, that can contain other leaf or composite components. From the point of view of the client, all components are treated the same, which greatly simplifies the client code.

jase
A: 

Template pattern is commonly used in the implementation of dotnet events to set up preconditions and respond to postconditions. The degenerate case is

void FireMyEvent(object sender, EventArgs e) 
{
  if (_myevent != null) _myEvent(sender, e);
}

in which the precondition is checked. In this case the precondition is that handlers can be invoked only when at least one has been bound. (Please don't tell me I should invoke the handlers asynchronously. I know that. I am illustrating Template pattern, not asynchronous programming technique.)

A more elaborate precondition might involve checking a property that governs the firing of events.

Template pattern is also commonly used to implement hooks, for example

public virtual void BeforeOpenFile(string filepath)
{
  //stub
}
public virtual void AfterOpenFile(string filepath)
{
  //stub
}
public sealed void OpenFile(string filepath) 
{
  BeforeOpenFile(filepath); //do user customisable pre-open bits
  //do standard bits here
  AfterOpenFile(filepath); //do user customisable post-open bits
}
Peter Wone
A: 

The Command pattern is used everywhere you have Undo functionality.

Martijn
A: 

If you're familiar with Python, check out the Twisted framework. http://twistedmatrix.com/trac/

Vasil
+1  A: 

Perhaps a good example, as pointed out in the Head First Design Patterns too, is the JAVA Swing API which implements the Observer pattern. More specifically, the JButton (or the superclass AbstractButton) is the Observable class and provides methods to add and remove "Observers", or "Listeners" as they are called in Swing.

Jahanzeb Farooq