C Sharp Programming/Design Patterns

Design Patterns are common building blocks designed to solve everyday software issues. Some basic terms and example of such patterns include what we see in everyday life. The design patterns are broadly classified into 3 types:

1. Creational: These patterns are designed for class instantiation. They can be either class-creation patterns or object-creational patterns.

2. Structural: These patterns are designed with regard to a class's structure and composition. The main goal of most of these patterns is to increase the functionality of the class(es) involved, without changing much of its composition.

3. Behavioral: These patterns are designed depending on how one class communicates with others.

Factory Pattern
The factory pattern is a method call that uses abstract classes and its implementations, to give the developer the most appropriate class for the job.

Lets create a couple of classes first to demonstrate how this can be used. Here we take the example of a bank system.

This Transaction class is incomplete, as there are many types of transactions:


 * Opening
 * Credits
 * Withdrawals
 * Transfers
 * Penalty
 * Correction
 * Closure

For this example, we will take credit and withdrawal portions, and create classes for them.

The problem is that these classes do much of the same thing, so it would be helpful, if we could just give it the values, and it will work out what class type we require. Therefore, we could come up with some ways to distinguish between the different types of transactions:


 * Positive values indicate a credit.
 * Negative values indicate a withdrawal.
 * Having two account numbers and a positive value would indicate a transfer.
 * Having two account numbers and a negative value would indicate a closure.
 * etc.

So, let us write a new class with a static method that will do this logic for us, ending the name :

Now, you can use this class to do all of the logic and processing, and be assured that the type you are returned is correct.

Singleton
The singleton pattern instantiates only 1 object, and reuses this object for the entire lifetime of the process. This is useful, if you wish the object to maintain state, or if it takes lots of resources to set the object up. Below is a basic implementation:

The property will expose the same instance to all callers. Upon the first call, the object is initialised and on subsequent calls this is used.

Examples of this pattern include:
 * (Generic settings reader)
 * (Application object in ASP .NET)
 * (Cache object in ASP .NET)
 * (Server object in ASP .NET)