Composite Design Pattern in C#
02 August 07 09:08 AM | ppopadiyn | 0 Comments   
  1. Introduction

The composite pattern is very simple pattern that has significant implication. The fundamental structure of the Composite pattern is shown on the next figure:

 

 

 

 

 

 

 

 

The base class Shape has two inheritors: Rectangle and Ellipse. The third inheritor is the composite. ComposeShapes holds a list of Shapes. An instance of ComposeShapes appears to be a single Shape. It can be passed to any function that takes a Shape, and it will behave like one.

2. Implementation

There are different implementations of the Composite pattern. I will show you one of them with the following example. Consider the following situation. Imagine we have a small company, which started with a single person (the boss). After some period of time he hired three people to help him with the business. Two of them became vice-presidents and the third became the finance manager (for example). Soon each of them hired new staff. As the success continues the company grows till the following sample structure is reached:

2.1 The IEmployee interface.

Each of the company members should receive a salary, have a boss and subordinates and should of course have some specific position. So in that case we will define a single interface named IEmployee that will declare all actions that each company member could implement.

public interface IEmployee
{
       string Name { get; set; } // get name
       decimal PricePerHour { get; set; } 
       Position Position { get; set; }  // get position 
       IEmployee Boss { get; set; } // get boss
       List<IEmployee> Subordinates { get; }
       decimal GetSalary( decimal workHours ); // get salary
       void Add( IEmployee employee );
       void Remove( IEmployee employee );
}

Note that I have declared two additional methods (Add and Remove) in the IEmployee interface which functions are for adding and removing subordinates. These two functions are quite IMPORTANT, because they may cause overhead of the developer who design the Composite pattern. Why? I will discuss later. Now let’s come back to our implementation. I will define an enumerated type to create a structured set of constants that will represent some available positions in the company.

public enum Position
{
       None,
       Boss,
       VicePresident,
       Secretary,
       MainManager,
       SalesManager,
       Cleaner
}

2.2 BaseEmployee class.

Next we will implement our concrete BaseEmployee class that will store the name, salary (price per hour), position, parent (boss) and subordinates of the employee.

public class
BaseEmployee : IEmployee
{
       private string name;
       private decimal pricePerHour;
       private Position position;
       private IEmployee boss;
       private List<IEmployee > subordinates = new List<IEmployee >();
       public BaseEmployee( string name, decimal pricePerHour, IEmployee boss, Position position )
       { // Intialize all private fields ............ }
       
      
// Properties ......................
       public virtual void Add( IEmployee employee )
       {
              throw new InvalidOperationException( "Cannot add in base employee class" );
       }
       public virtual void Remove( IEmployee employee )
       {
              throw new InvalidOperationException( "Cannot remove from base employee clase" );
       }
       public virtual decimal GetSalary( decimal workHours )
       {
              return workHours * pricePerHour;
       }
}

It is obvious that the aim of the private field ‘subordinates’ is to keep a reference to each subordinate in the Collection of each Employee class. It also allows us to move downwards the chain from the president to each employee. But to keep our structure flexible enough we also need to move backwards to find out who an employee’s boss is. This is easy to implement, we just provide a constructor for each subclass that includes reference to the parent node - his/her boss. Of course for the boss of the company we will just pass ‘null’ to the constructor. The GetSalary method just gives us the salary of each employee. We also define some casual properties. Note that we do not implement the two problematic methods ‘Add’ and ‘Remove’, we only throw an exception in case these methods are called in the base employee class.

2.3 Employee class.

Our Employee class is a subclass of BaseEmployee and allow us to store subordinate employees as well. We will store them in generic List, named subordinates.

class Employee : BaseEmployee
{
       public Employee( string name, decimal pricePerHour, IEmployee boss, Position position )
              : base( name, pricePerHour, boss, position )
       {
       }
       public override void Add( IEmployee emp )
       {
              this.Subordinates.Add( emp );
       }
       public override void Remove( IEmployee emp )
       {
              this.Subordinates.Remove( emp );
       }
}

Here we finally implement the ‘Add’ and ‘Remove’ methods. If we make a summary, all these classes and methods could be represented in the following rough diagram:

 

Now we can start building our company structure. First we will create the president of the company, and then add his subordinates and their subordinates and etc.

3. Advantages, Disadvantages and Analyses.

The Composite pattern allows us define a class hierarchy of simple objects as well as some more complex composite objects, in each case they appear to be the same to the client. So the big advantages is that the nodes and leaves are handled in the same way. The Composite pattern also makes it easy to add new kinds of components to your collection, as long as they suppost similar interface. On the other hand this leads to a big disadvantage, your system will become too general. It will be hard to restrict certain classes where this normally is desirable. Sometime it is necessary a composition to have only specific components.

It is easy to add a new components to the structure, without changing the client code.

3.1. Explicit reference to the parent.

Holding references in the components to their parent is useful and can simplify the traversal of the tree (moving through all nodes (in this example – all employees) of the heirarchy), removing and adding new components. One available place where you could place this reference is in the ‘BaseEmployee’ class. And then all its subclasses can just inherit the reference and the methods that control it.

But in this case it is very important to keep synchronization between parents and children. That means, all successors should have a parent, and on the other hand this parent should have them for own children. The easiest way to do this is to change the parent of the given component when you add or remove components. If it is possible this feature should be implemented in the ‘Add’ and ‘Remove’ operations and then all this work will be done automaticly.

It is also possible to share a component. That mean one component may have more than one parent (in this case one employee may have more than one boss). But that case may lead to overhead.

3.2. The IEmployee interface.

One of the purpose of the Composite pattern is to hide the details of the class ‘Employee’. To do this the IEmployee interface should define as much as possible operations.

3.3. The ‘Add’ and ‘Remove’ operations.

Although in the interface ‘IEmployee’ we declare these two operation, there is a very important question: Which classes should implement these operations. Should we declare the operations ‘Add’ and ‘Remove’ in the ‘IEmployee’ interface (meaning that the ‘BaseEmployee’ class (the Component) must implement them)? Or, should we declare and define the operations only in the Composite class (Employee). The decision includes compromise between security and transparancy.

Consider the following situation: we have the same design as the example above, but suddenly we decided to derive the ‘BaseEmployee’ class and to create new components with specific characteristics. On the other hand only the composite class (‘Employee’) can add and remove components from the hierarchy. That mean that a non-leaf node can have a child-leaves added to it, but a leaf node cannot. So we want all components in the composite to have the same interface and to be treated equally. However that mean we will lose security because the clients may try to do foolish actions, like a adding and removing objects from the leaves.

If we declare and define the operations ‘Add’ and ‘Remove’ in the Composite class (Employee), we will win security, but on the other hand the Components and the Composition will have different interface.

3.4. Ordering Components.

In some programs, the order of the components may be important. If that order is somehow different from the order in which they were added, then the parent must do additional work to return them in correct order. For example, you might sort the collection alphabetically and return a new sorted collection.

3.5. Caching the result.

If you frequently ask for data that must be computed from a series of child components, it may be advantageous to cache these computed results in the parent. However, unless the computation is relatively intensive and you are quite certain that the underlying data has not changed, this may not be worth the effort.

4. Usage.

Use Composite pattern:

  • When you want to define a class hierarchy of simple objects or more complex composite objects.
  • When you want the clients to ignore the differences between the composite objects and the individual objects. The clients will treat equally all objects in a complex structure.

5. Conclusion.

The advantages are significant. Instead of duplicating the list management and iteration code in each of the clients, that code appears only once in composite class. So my advice is: use it ! ;)

How to validate file name using ReGex?
21 May 07 06:27 AM | ppopadiyn | 0 Comments   

There are many times when you need to validate a file name on your local machine. One powerful and flexible way is to use regular expressions. Suppose we have a TextBox named textBoxFileName where the user enter the FULL PATH of the file. You can handle the OnValidating event and to use the next snippet of code:

string error = String.Empty;         

string dirPattern = @"^[a-zA-Z0-9_]+:((\\|/)[^/\:*?<>|""]+){0,}(\\|/)[^/\:*<>?|""]+" + fileNameExtension + "?$";           

Match fileMatch = Regex.Match( textBoxFileName.Text, dirPattern ); 
 
So lets examine what we are doing here: First we check to see if the string starts with a drive name ( for example: e:\ or e:/ ). Then the user can enter any character or a sequence of characters without those which are not allowed ( /,\,:,*,?,<,>,|," ).
Note that when you tell the compiler that the string is a literal using the @ character, you cannot escape a " with the escape character \. When using the @ character to make a string literal, you can escape a quotation mark with another quotation mark.

if ( !fileMatch.Success )
{
     error =
"Invalid file name!";
     e.Cancel =
true;
}

Next we should validate the drive name. A simple way is to use the DriveInfo class.

                                                                                                                  

How to create objects using the class factory pattern?
20 May 07 11:48 PM | ppopadiyn | 0 Comments   

I. Introduction

In object - oriented computer programming, a factory object is an object for creating other objects. A factory object typically has a method for every kind of object it is capable of creating. These methods optionally accept parameters defining how the object is created, and then return the created object. Factory objects are used in situations where getting hold of an object of a particular kind is a more complex process than simply creating a new object.

II. Implementing the pattern: ClassFactory class.

There are two main approaches to implement the factory pattern: using one factory class or using multiple factory classes.
The next example represents the case where one factory is used to produce all of the related products:

     

public interface IEmployee

{

     string ShowMe();

     double Salary

     {

          get;

     }

}

     

public class OfficeManager : IEmployee

{

     string IEmployee.ShowMe()

     {

         "Office Manager";

     }

     double IEmployee.Salary

     {

         get

         {

             return 1000.0;

         }

     }   

}

     

public class Banker : IEmployee

{

     string IEmployee.ShowMe()

     {

          return "Banker";

     }

     double IEmployee.Salary

     {

          get

          {

             return 500.0;

    }

     }

}

     

public class EmployeeFactory

{

     public IEmployee CreateEmployee( string position )

     {

         switch ( position )

         {

             case "Office Manager":

                   return new OfficeManager();

             case "Banker":

                   return new Banker();

         }

         return null;

     }

}

     

Note that each class has its own factory. In this example the class factory implements the method CreateEmployee that returns objects. The most important thing is that the method is declared with IEmployee as its return type, so it can return an instance of any class that implements that interface. Now when the class factory is defined to create an object is a simple work:

     

EmployeeFactory factory = new EmployeeFactory();

IEmployee emp1 = factory.CreateEmployee( "Office Manager" );

IEmployee emp2 = factory.CreateEmployee( "Banker" );

Console.WriteLine( "Position: {0}, salary: {1}.", emp1.ShowMe(), emp1.Salary );

Console.WriteLine( "Position: {0}, salary: {1}.", emp2.ShowMe(), emp2.Salary );

     

The most important thing is that when we need to create new products, we should supply the factory with new code, but no changes are required on the client side. What happen when we need to use multiple factories? The solution just adds the abstract class for the factory and two concrete subclasses. And finally we could create an EmployeeCollector class that serves as a bridge between the clients and the factory.

     

public abstract class Factory

{

     public abstract IEmployee CreateEmployee();

}

     

public class OfficeManagerFactory : Factory

{

     public override IEmployee CreateEmployee()

     {

          return new OfficeManager();

     }

}

     

public class BankerFactory : Factory

{

     public override IEmployee CreateEmployee()

     {

          return new Banker();

     }

}

     

public class EmployeeCollector

{

     public IEmployee CollectEmployee( Factory factory )

     {

          return factory.CreateEmployee();

     }

}

     

Factory manager = new OfficeManagerFactory();

Factory banker = new BankerFactory();

IEmployee emp1 = new EmployeeCollector().CollectEmployee( manager );

IEmployee emp2 = new EmployeeCollector().CollectEmployee( banker );

Console.WriteLine( "Position: {0}, salary: {1}.", emp1.ShowMe(), emp1.Salary );

Console.WriteLine( "Position: {0}, salary: {1}.", emp2.ShowMe(), emp2.Salary );

     

For a simple example like this, the first approach using one factory is easier to implement. However, there are cases where it's preferable to have multiple factories. The objects may be grouped into families of products, or you may have a distributed application where it makes sense for different developers to provide their own factory classes