11 June 2007

Command Pattern Example
Recently i asked to add a functionality to an existed code platform, some of the functionality execute before the operational platform and some after.
This leads to massive change all over the code, in order to refine the change i use the command pattern

The Solution

Create an interface which define the command call it IWrapCommand, Define the functions as command, part of the functions refer as before function and the other as after function.
The OperationWrapper use to wrap the code platform with the commands.
The before command execute in the constructor and the after command execute in the dispose.
It preferred to use the using(){} code pattern to wrap the code platform.
Here the code,
namespace OperationWrapping{ public interface IWrapCommand { void Execute(); }}

using System;
using System.Collections.Generic;
using System.Text;

namespace OperationWrapping
{
/// <summary>
/// The class add the abillity of wrapping a operational process with
/// commands before the operation process executin and after.
/// </summary>
public class

OperationWrapper : IDisposable
{
#region Data members
private List< IWrapCommand > m_commandsAfter = null;
#endregion

public OperationWrapper(IWrapCommand i_commandBefore ,
IWrapCommand i_commandAfter)
{
if (i_commandAfter != null)
{
m_commandsAfter = new List< IWrapCommand >();
m_commandsAfter.Add(i_commandAfter);
}

if (i_commandBefore != null)
{
i_commandBefore.Execute();
}
}

public OperationWrapper(List<IWrapCommand> i_commandsBefore ,
List<IWrapCommand> i_commandsAfter)
{
m_commandsAfter = i_commandsAfter;

if (i_commandsBefore != null)
{
foreach (IWrapCommand m_command in i_commandsBefore)
{
m_command.Execute();
}
}
}

///<summary>
///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///</summary>
///<filterpriority>2</filterpriority>
public void Dispose()
{
if (m_commandsAfter != null)
{
foreach (IWrapCommand m_command in m_commandsAfter)
{
m_command.Execute();
}
}

GC.SuppressFinalize(this);
}
}
}


namespace OperationWrapping
{
public interface IWrapCommand
{
void Execute();
}
}

AlfaCommand alfaCommand = new AlfaCommand();
DirtyCommand dirtyComamnd = new DirtyCommand();

using (OperationWrapper m_OperationDirty = new OperationWrapperalfaCommand , dirtyComamnd))
{
if (alfaCommand.IsContinue)
{
// the old code wrapped
}
}

No comments: