Click here to Skip to main content
6,629,885 members and growing! (23,206 online)
Email Password   helpLost your password?
Development Lifecycle » Design and Architecture » General     Intermediate

Behavioral Patterns: Writing Command pattern with c#

By Francesco Carata

Writing Command pattern with c# (real example)
C# 2.0.NET 2.0, WinXP, VistaVS2005, Architect, Dev, Design
Posted:9 Jul 2007
Updated:23 Aug 2007
Views:22,503
Bookmarked:52 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
14 votes for this article.
Popularity: 3.99 Rating: 3.48 out of 5
1 vote, 7.1%
1
2 votes, 14.3%
2
2 votes, 14.3%
3
2 votes, 14.3%
4
7 votes, 50.0%
5

Introduction

This article shows how to implement the behavioral pattern Command with c# 2.0 and .NET in a real case.

What's a Design Pattern?

A design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

What's a Behavioral Design Pattern

Behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.

Purpose

The Command pattern is a design pattern in which objects are used to represent actions. A command object encapsulates an action and its parameters.

Structure

Command, declares an interface for executing an operation.

Concrete Command, defines a binding between a Receiver object and an action. Implements Execute by invoking the corresponding operation(s) on Receiver.

Client, creates a ConcreteCommand object and sets its receiver.

Invoker, asks the command to carry out the request.

Receiver, knows how to perform the operations associated with carrying out the request.

Real case

This example shows how to fill different controls with the Command pattern. The source for each control is the file of Custom Resources.

NOTE: each control implements a different binding logic but across the Command pattern this is hidden to client.

Let's write the code of Command

1) Write the Command

This interface contains the method to call for executing Receiver code

    // Command
    public interface ICommand    
    {
        void Execute();
    }

2) Write the Concrete Command

This class defines a binding between a Receiver and the Execute Command action

    // Concrete Command
    public class ConcreteCommand: ICommand
    {
        private IFiller _filler;

        public ConcreteCommand(IFiller filler)
        {
            _filler = filler;
        }

        public void Execute()
        {
            _filler.Fill();
        }
    }

3) Write the "Common Receiver"

This interface contains the common method for all controls to bind. This interface provides a common aspect for all controls that want to use Command

    public interface IFiller
    {
        void Fill();
    }

4) Write the "Invoker"

This class allow to call the Execute method for each item that implements IFiller

      // Invoker
    public class Invoker
    {
        private IFiller[] _filler;

        public Invoker(IFiller[] filler)
        {
            _filler = filler;
        }

        public void Execute()
        {
            ICommand command;
            foreach (IFiller item in _filler)
            {
                command = new ConcreteCommand(item);
                command.Execute();
            }

        }
    }

Let's write the code of Client

1) Write the receiver(s)

The following Custom Controls (Label, ListBox, ListView) are controls that derive from Label, ListBox and ListView controls.

This controls implement the "Common Receiver" interface for implementing logic of binding

    // Receiver
    public class CustomLabel: Label, IFiller
    {
        public void Fill()
        {
            this.Text = Resources.ResourceManager.GetString(this.Name);
        }
    }

     // Receiver
    public class CustomListBox: ListBox, IFiller
    {
        public void Fill()
        {
            this.Items.Clear();
            int index=1;
            string item = Resources.ResourceManager.GetString(
                string.Format("{0}{1}{2}", 
                this.Name, 
                "_", 
                index.ToString()));
            while (item != null)
            {
                this.Items.Add(item);
                index++;
                item = Resources.ResourceManager.GetString(
                string.Format("{0}{1}{2}",
                this.Name,
                "_",
                index.ToString()));
            }
        }
    }

    // Receiver
    public class CustomListView: ListView, IFiller
    {
        public void Fill()
        {
            this.Columns.Clear();
            int index = 1;
            string item = Resources.ResourceManager.GetString(
                 string.Format("{0}{1}{2}",
                 this.Name,
                 "_",
                 index.ToString()));
            while (item != null)
            {
                this.Columns.Add(item);
                index++;
                item = Resources.ResourceManager.GetString(
                string.Format("{0}{1}{2}",
                this.Name,
                "_",
                index.ToString()));
            }
        }
    }

2) Write the Client

The Client call the Invoker that invoke the Command

After insert Custom Controls in a form, I wrote a recursive functions to find controls that implement IFiller and then I call the Invoker on List of IFiller controls.

    public partial class Form1 : Form
    {
        private List _filler;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _filler = new List();
            searchControl(this.Controls);
            
            // Client
            Invoker invoker = new Invoker(_filler.ToArray());
            invoker.Execute();
        }

        private void searchControl(Control.ControlCollection ctrCollection)
        {
            foreach (Control ctr in ctrCollection)
            {
                IFiller fctr = ctr as IFiller;
                if (fctr != null)
                    _filler.Add(fctr);
                if (ctr.Controls.Count > 0)
                    searchControl(ctr.Controls);
            }
        }
    }

History

This is the first iteration of this code, please provide any feedback as to whether you have used this or not or any problems that anyone has found with it!

About Francesco Carata

.NET Software Developer for BeyondTrust Corporation.

I live in Turin, Italy.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Francesco Carata


Member

Occupation: Web Developer
Location: Italy Italy

Other popular Design and Architecture articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
GeneralWhat problem do your code solve? PinmemberVerifier9:54 26 Aug '08  
GeneralInteresting Idea Pinmembermerlin9815:27 24 Aug '07  
GeneralInvoker? Pinmemberdejavudesi4:50 23 Aug '07  
GeneralRe: Invoker? PinmemberFrancesco Carata21:18 23 Aug '07  
GeneralSo what is Command Pattern? Pinmemberzhi-chen7:23 13 Jul '07  
GeneralRe: So what is Command Pattern? PinmemberFrancesco Carata7:26 14 Jul '07  
AnswerRe: So what is Command Pattern? Pinmembermike griggs23:51 1 Aug '07  
GeneralRe: So what is Command Pattern? PinmemberFrancesco Carata23:56 1 Aug '07  
Generalmultiple casts PinmemberMeile2:14 10 Jul '07  
GeneralRe: multiple casts PinmemberFrancesco Carata2:26 10 Jul '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Aug 2007
Editor:
Copyright 2007 by Francesco Carata
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project