Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Friday, March 29, 2013

Design Pattern: .NET DI (IoC) Frameworks


Having some spare time and interest, I decided to learn a bit more about the features of modern .NET IoC frameworks. Being aware of what’s available always helps, and I haven’t yet seen a comprehensive feature comparison.
For the comparison, I have selected the frameworks that I feel to be most documented and popular:
If you feel that your framework should be here, just send me the values for all feature columns, and I’ll add it.

0. Terminology

The first thing I learned is that common concepts are sometimes named differently between the frameworks.
So I think it makes sense to start with some terminology.
Components are classes registered within the container. They can be instantiated by the container to satisfy servicedependencies of other components. Services are what components provides and depends on.
In most of the cases services are interfaces, and components are classes implementing them.
Autowiring is an automatic detection of dependency injection points. If the framework is able to  match the constructor parameter types with registered services and provide these services, it is an example of autowiring.
Transient components, as compared to singletons, are created each time they are requested from container. The exact term used for transients differs quite much between frameworks.
Automatic registration is a way to automatically detect and register components within an assembly (or larger environment). It can also be called batch registration.

1. Licensing and core size

All reviewed frameworks work under .NET 2.0, and have liberal licenses allowing commercial and open-source usage.
The first table lists the reviewed frameworks with some basic parameters.
The color map is easy: green is great, yellow is ok, red is bad. All colors are extremely subjective, things bad for me may mean that I am doing something wrong.
I do not feel library count or size to be important for developments, so no red points this time.
Ninject is the most interesting case, since it has a very naive auto-wiring implementation by default. However, it has an official Ninject.Extensions.AutoWiring library, so in all following tables I included its features in Ninject functionality.

2. Container configuration

The first thing to do with container is to register something in it. So let’s review the configuration options provided by various framework.
As you can see, all frameworks support programmatic registration. Even better, most of them have fluent interfaces for registration API. Spring.Net and Castle are behind others in this regard, since Spring.Net API is somewhat cumbersome and not fluent, while Castle does not support fluent registration in RC3.
As I noted before, automatic registration is a way to register all types in given set of assemblies/namespaces based on attributes or other conventions. I find it very useful, since the convention-driven approach saves time on configuration and lessens a chance of a configuration error.
Castle’s BatchRegistrationFacility is obsolete and well-hidden, also it uses GetExportedTypes instead of GetTypes (The Sin of Shallow Digging), so it’s useless if you want to hide implementations and expose only interfaces. For Spring.NET I didn’t find an easy way, but it still might be possible, so you can correct me on this one.
Some people consider attributes to be POCO, some not, and I tend to agree with the latter when we are talking about DI frameworks. So no red points or yellow points if framework has no attributes, this column just for your information.
As for XML, I have a very strong opinion — only if actually needed, only as much as actually needed. Fortunately, no one of reviewed frameworks required XML (while most of them support it when needed). Spring.Net is somewhat differently oriented for this question, since its XML API is a better, more documented and encouraged approach. However, since Spring is a Java port, the approach is probably a compatibility heritage.

3. Basic injection/autowiring

The second thing after configuring the framework is knowing what exactly can be automatically injected. And, as I explained earlier, autowiring is just a name for framework-discovered injection points.
Basic constructor injection works great in all frameworks. For property injection Unity and StructureMap require explicit opt-in and treat the dependency as mandatory, which is a bit counterintuitive and does not provide any benefit over constructor injection.
As for multiple constructors, I really like the Castle/Autofac choice of constructor with most resolvable parameters. This is precisely what the human programmer will do, given a number of constructors and dependencies. With approach taken by Unity and StructureMap, it is harder to keep object DI-ignorant — you have to think whether your most-parameter constructor is resolvable, add DI-specific attributes or specify the constructor explicitly in the XML/code configuration.
The most interesting behavior was shown by the Spring.Net — it selected default (no-parameter) constructor first, and only if default did not exists, Spring went to the most resolvable.
Recursive dependency resolution is, in my opinion, one of the most important things in a DI framework. In a large project, when you have a lot of components and services, solving recursion easily is a must. In my tests only Castle and Autofac gave a useful error message, all other frameworks just crashed with unrecoverable StackOverflowException, which is a bad, bad thing to get in automatic test runner.

Design Pattern: IOC and DI part 2

What is Inversion of Control?

According to Wikipedia “Inversion of Control, or IoC, is an abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming”.
The latter part of that quote is interesting. According to it Inversion of Control is a way to invert the flow of control in comparison to procedural programming.
What that means is that in procedural programming a chunk of code that uses, or consumes, another chunk of code is in control of the process.
It knows exactly what piece of code, what method in what class, it uses. And in doing so it is also quite likely that it knows about some implementation details in the code it uses.

An example

One example of such a scenario and of such a dependency is when a class, illustrated as X below, uses another class Y.

The consumer, X, needs the consumed class, Y, to accomplish something. That’s all good and natural, but does X really need to know that it uses Y?
Isn’t it enough that X knows that it uses something that has the behavior, the methods, properties etc, of Y without knowing who actually implements the behavior?
By extracting an abstract definition of the behavior used by X in Y, illustrated as I below, and letting the consumer X use an instance of that instead of Y it can continue to do what it does without having to know the specifics about Y.

In the illustration above Y implements I and X uses an instance of I. While it’s quite possible that X still uses Y what’s interesting is that X doesn’t know that. It just knows that it uses something that implements I.
That could be Y, but it could also be A, B or C given that they implement I. Of course this discussion is rather abstract at the moment, but we’ll get to how to implement this in a second using either Dependency Injection or Service Locator.
For now, let’s just assume that we can and that we can change what implementation of I X uses at runtime. What benefits can we get from that?

Benefits of Inversion of Control

Well, first of all X is not dependent on Y anymore and it’s therefore less likely that we’ll have to make changes to X when we make changes in Y as we’re less likely to write code in X that relies on implementation details in Y.
Furthermore X is now much more flexible as we can change which implementation of I it uses without changing anything in X.
Perhaps Y is a component for sending e-mails and we want X, who used to send e-mails, to start sending tweets instead using Z who also implements I. Since X no longer relies specifically on Y but on something that implements I we don’t have to modify anything in X.
Another benefit of inversion of control is also that we can isolate our code when creating unit tests.
Suppose, as before, that X used Y to send messages which Y did in the form of e-mails using an SMTP-server. When creating unit test, which should only test a single unit of code, we want to be able to test the logic in X without having to care about the component that sends messages, and we most definitely don’t want our tests to fail because Y doesn’t have access to an SMTP server.
Having used inversion of control X doesn’t rely on Y anymore but on an implementation of I that just happens to be Y.
That means that we, in the setup phase of our tests, can change it so that X uses a different implementation of I, such as a mock object which doesn’t send any messages at all, and which also allows us to check that X has used it in a correct way.

Applying Inversion of Control – A sample scenario

Enough with the X and the Y and I! Let’s look at a more concrete scenario.
We have a class named OrderService which is used for processing orders.
It has a method named AcceptOrder which receives an Order object, validates that it is valid according to the business rules (it may for instance check that the order’s shipping address is a valid address and that there are enough items in stock) and then, given that the order is valid, saves it to a database using another class named OrderDatabase.

The code for OrderService looks like this:
public class OrderService
{
    public void AcceptOrder(Order order)
    {
        //Domain logic such as validation

        new OrderDatabase().SaveOrder(order);
    }
}
Notice line seven above where AcceptOrder creates a new instance of the OrderDatabase class and then saves the order using it’s SaveOrder method. This might not be the most realistic scenario. In the real world SaveOrder could be static, making line seven in the example look like this:
OrderDatabase.SaveOrder(order);
Or there might a singleton implementation of OrderDatabase making line seven look like this:
OrderDatabase.Instance.SaveOrder(order);
Either way it doesn’t matter. What matters is that AcceptOrder relies on OrderDatabase which is something very concrete.
How OrderDatabase is implemented isn’t very important as long as we realize that relying on it is inflexible and bad for testability. For the sake of this example let’s assume it’s SaveOrder method looks like this:
public void SaveOrder(Order order)
{
    throw new ApplicationException("I need a database to work");
}
This will make it very hard to test the business logic in OrderService’s AcceptOrder method since it will call the SaveOrder method which in turn throws an exception.
To fix this we apply Inversion of Control by creating an abstract definition of the behavior in OrderDatabase that OrderService needs in the form of the interface IOrderSaver and making AcceptOrder use an instance of IOrderSaver instead of an instance of OrderDatabase.

OrderService no longer knows about the OrderDatabase class. It just uses an instance of the IOrderSaver interface of which OrderDatabase is one of possibly many implementation.
In fact we could easily change it so that OrderService instead uses a class that saves orders to XML files instead, without changing a single line of code in OrderService.
Or to a class that still saves to a database but that has been extended with logging.
Or to a composite that saves both to a database and to an XML file. Or to…

That’s all good, but how does OrderService get this instance of IOrderSaver you ask?
There would be little point in using the IOrderSaver interface if OrderService still had to know how to instantiate a concrete implementation of it, so we need a way for OrderService to get an instance of IOrderSaver at runtime without knowing about any concrete implementations.
There are a couple of ways to do that. Let’s begin by looking at Dependency Injection.

Dependency Injection

Using Dependency Injection we inject an instance of IOrderSaver into OrderService when we use it.
This could either be done using constructor injection, where we supply the instance to OrderService’s constructor, or property injection where we supply it to OrderService after it has been instantiated by setting a property on it.
In the diagram below I’ve tried to illustrate constructor injection.

Notice how OrderService has a constructor which requires an instance of IOrderSaver as a parameter. In code this could be implemented like this:
public class OrderService
{
    private IOrderSaver orderSaver;

    public OrderService(IOrderSaver orderSaver)
    {
        this.orderSaver = orderSaver;
    }

    public void AcceptOrder(Order order)
    {
        //Domain logic such as validation

        orderSaver.SaveOrder(order);
    }
}
As you can see in the example code above OrderService’s constructor requires an instance of IOrderSaver which it stores in a field. When invoked the AcceptOrder method uses this injected instance to save the order.
Should we want to be able to instantiate OrderService without supplying an IOrderSaver there is of course nothing stopping us from creating another constructor which sets the orderSaver field to a default implementation.
public OrderService()
{
    this.orderSaver = new OrderDatabase();
}
While this means that OrderService still knows about which implementation of IOrderSaver it uses when instantiated with this constructor we are still able to change what implementation it uses using the other constructor, for instance when we are creating unit tests.
I’m not saying this is a good idea, but it is possible and definitely better than not being able to change how OrderService saves orders at all.

Service Locator

While I think Dependency Injection is superior in just about any situation there is also another way to implement Inversion of Control, using a Service Locator.

In the diagram above OrderService doesn’t know about OrderDatabase but it does know about an instance of the concrete class ServiceLocator which in turn knows about OrderDatabase.
When AcceptOrder is invoked it will ask ServiceLocator for an instance of IOrderSaver which will supply one based on how we have configured it.
Using this approach OrderService could be implemented like this:
public class OrderService
{
    public void AcceptOrder(Order order)
    {
        //Domain logic such as validation

        OrderSaverFactory.GetOrderSaver().SaveOrder(order);
    }
}
A simple implementation of ServiceLocator would be to have it supply an instance of a default implementation of IOrderSaver unless we specifically tell it to supply another instance, like this:
public class ServiceLocator
{
    public static IOrderSaver OrderSaver { get; set; }

    public static IOrderSaver GetOrderSaver()
    {
        if (OrderSaver == null)
            OrderSaver = new OrderDatabase();

        return OrderSaver;
    }
}
I find the Service Locator approach to be much more messy than Dependency Injection and it makes unit tests harder to set up, but there might be a few situations where Dependency Injection may be impractical. Then it’s good to still be able to apply Inversion of Control by using Service Locator.

references:http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/

Design Pattern : IOC and DI Part 1

The problem 

Any good architecture always stands on the base that components are loosely coupled… let me stress the point truly loosely coupled. Let’s try to understand this with a scenario and how we normally approach this problem using pure object oriented way.

Consider a scenario where we have a customer class which needs to perform insert operation on database. The customer class should be customizable to save in either Sql server or oracle database. In future we should also be able to add new databases with out disturbing the customer class.

Below is what we will do. Define two classes one for SQL server and other for Oracle. Both these classes inherit from some kind of same interface ‘Idatabase’. The customer class points to this interface. So the customer class is theoretically shielded from the concrete implementation of SQL Server or oracle. But because the object creational activity needs to be done by the customer class it still needs to be aware of the concrete classes.
 



Figure: - General loosely coupled thinking
 
This is what will happen in actual implementation as shown in figure ‘Concrete classes’. The customer class will be creating objects of either oracle or SQL server depending on condition. That means the customer class is exposed to the concrete classes which defeats the purpose of interface. Any change in the database classes will lead to compiling of the customer class.
 



Figure :- Concrete classes


Creational patterns


The next thing comes in mind is creation patterns. If we can introduce a factory who takes the creational aspect of the concrete classes thus isolating the concrete classes from the customer class.

Here are the issues with factory which makes us force to think about some other solutions:-

• Everything is hardcoded: - The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.
• Interface dependent: - The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.
• Factories are custom: - They are very much custom to a particular implementation.
• Everything is compile time: - All dependent objects for an object in factory have to be known at compile time.

I will not be explaining factory pattern in case you are not aware of you can read the same in my previous article SoftArchInter1.aspx

Ok, I will show you a magic…Rather than writing those huge line of code for factory…lets go the DI way (Dependency injection).
 


Dependency Injection


Rather than writing factory pattern, how about injecting the object directly in to the customer class. So let the customer class references the interface and we should be able to inject the concrete type in to the customer class. With this the customer class does not need to use the new keyword and is complete decoupled from the concrete classes.





Figure: - Dependency injection
 
Injection can be done using containers. So basically you need to put both the classes in to the container and the container will create object and inject the same in to the other class.
 




Figure: - Containers
 
With this your customer class does not need to worry about creating objects and knowing the concrete objects.
 


Solving problem using UNITY block


Now that we know the benefit of containers we will explore unity application block which helps us to achieve dependency injection.
 


Download and installing Unity


The first step is to download the unity application block from http://msdn.microsoft.com/en-us/library/cc468366.aspx  and install the same. Depending on whether you have 2008 or 2005 the documentation will vary. For this tutorial I will be using VS 2005 because majority professionals are still using 2005.





Figure: - unity block installed
 
Once you install the block you should be able to see the same in Microsoft patterns and practices.

The first thing you need to do is to get the references of at least two components Unity and Unity configuration.
 



Figure: - Add referenced to Unity components
 
Once you have got reference to the components import the “Microsoft.Practices.Unity” namespace in to your code as shown in figure ‘Import unity namespace’.




Figure: - Import unity namespace
 

Defining the common interface


As said previously we should be able to inject SQL Server database object or oracle database object in the customer class. So as a good practice we will inherit the SQL server implementation and oracle implementation from a common interface ‘Idatabase’.
 



Figure: - Database interfaces
 

Providing the injection gateway


In the customer class we will reference the interface and expose the public property using [Dependency] attribute. This exposure is essential for the unity container. Unity container needs some kind of gateway by which it can inject the object. So what we have done is we have exposed the interface ‘iDatabase’ publicly. There are lot of other ways by which we can achieve the same you can read my previous article on the different ways of providing injection gateways for containers IOCDI.aspx  .





Figure: - Providing injection gateway
 

Defining the config file


To achieve high customization unity application allows us to specify how the injection will work in the config files ( web.config and app.config ). As this example is a windows command application we will be defining an app.config file.

You can see below a simple template of App.config file from unity perspective. The Configsection is compulsory and keep it as it is. The important section to be noted is the types section which comes under container section. In this we specify which interfaces map to which concrete class. The unity container creates object from this section and inserts in to the customer object through the dependency attribute.
 



Figure: - App.config file
 

The client code


The client code is pretty simple. The first step us we create the unity container object. In the second step we read the unity section. In step 3 we configure the container using the unity section data.

In step 4 we tell the container to create the customer object. This is the most important step of all. In this the container using the config data and the dependency attribute injects either the SQL server database object or oracle database object in to the customer class. This object creation depends on what is defined in the app.config file.

Finally in step 5 we call the save method
 



Figure: - Client code
 

The actual internal working


So what happens internally in the container is that the unity container creates the object of either oracle or SQL server data objects and injects in to the customer class through the dependency defined attribute.
 



Enter the real world of loosely coupling
 

So if you define the ‘clsSqlServer’ class it will create the object of ‘clsSqlServer’ and inject it in to the customer class. If you define the ‘ClsOracle’ class it will inject the ‘clsOracle’ object. You can see in figure ‘The real fun’ how easy it to change implementation by just modifying the config file type sections
 



Figure: - The real fun

Monday, May 7, 2012

Design Pattern : Command patterns Implementation

Command pattern allows a request to exist as an object. Ok let’s understand what it means. Consider the figure ‘Menu and Commands’ we have different actions depending on which menu is clicked. So depending on which menu is clicked we have passed a string which will have the action text in the action string. Depending on the action string we will execute the action. The bad thing about the code is it has lot of ‘IF’ condition which makes the coding more cryptic.
Figure: - Menu and Commands
Command pattern moves the above action in to objects. These objects when executed actually execute the command.
As said previously every command is an object. We first prepare individual classes for every action i.e. exit, open, file and print. Al l the above actions are wrapped in to classes like Exit action is wrapped in ‘clsExecuteExit’ , open action is wrapped in ‘clsExecuteOpen’, print action is wrapped in ‘clsExecutePrint’ and so on. All these classes are inherited from a common interface ‘IExecute’.
Figure: - Objects and Command
Using all the action classes we can now make the invoker. The main work of invoker is to map the action with the classes which have the action.
So we have added all the actions in one collection i.e. the arraylist. We have exposed a method ‘getCommand’ which takes a string and gives back the abstract object ‘IExecute’. The client code is now neat and clean. All the ‘IF’ conditions are now moved to the ‘clsInvoker’ class.

Figure: - Invoker and the clean client

Example 2

Our implementation.

Sample Code

BaseCommand is abstract base class used to define contract.

  1. public abstract class BaseCommand  
  2. {  
  3.         protected Transaction _transaction;  
  4.   
  5.         public abstract int Execute(Transaction transaction);  
  6.   
  7.         public abstract int Undo();  
  8. }  
ConcreteCommandDeposit and ConcreteCommandWithdraw are the concrete command as well as Receiver classes.

  1. public class ConcreteCommandDeposit : BaseCommand  
  2. {  
  3.         #region Command Members  
  4.   
  5.         public override int Execute(Transaction transaction)  
  6.         {  
  7.             this._transaction = transaction;  
  8.             _transaction.BalanceAmount += _transaction.Amount;  
  9.             return _transaction.BalanceAmount;  
  10.         }  
  11.   
  12.         public override int Undo()  
  13.         {  
  14.             _transaction.BalanceAmount -= _transaction.Amount;  
  15.             return _transaction.BalanceAmount;  
  16.         }  
  17.  
  18.         #endregion  
  19. }  

  1. public class ConcreteCommandWithdraw : BaseCommand  
  2. {  
  3.         #region Command Members  
  4.   
  5.         public override int Execute(Transaction transaction)  
  6.         {  
  7.             this._transaction = transaction;  
  8.             _transaction.BalanceAmount -= _transaction.Amount;  
  9.             return _transaction.BalanceAmount;  
  10.         }  
  11.   
  12.         public override int Undo()  
  13.         {  
  14.             _transaction.BalanceAmount += _transaction.Amount;  
  15.             return _transaction.BalanceAmount;  
  16.         }  
  17.  
  18.         #endregion  
  19. }  
CommandInvoker class encapsulates call to command object and used to invoke command.

  1. public class CommandInvoker  
  2. {  
  3.         private BaseCommand _Command { get; set; }  
  4.          
  5.         public CommandInvoker(BaseCommand command)  
  6.         {  
  7.             this._Command = command;  
  8.         }  
  9.   
  10.         public int ExecuteCommand(Transaction param)  
  11.         {  
  12.             return _Command.Execute(param);  
  13.         }  
  14.   
  15.         public int UndoCommand()  
  16.         {  
  17.             return _Command.Undo();  
  18.         }  
  19. }  
Transaction class is just a DTO used to pass parameters to the commands. This is not a part of Command Pattern.

  1. public class Transaction  
  2. {  
  3.         public int Amount { get; set; }  
  4.   
  5.         public int BalanceAmount { get; set; }  
  6. }  
Following is how clients will use the command pattern to invoke commands.

  1. static void Main(string[] args)  
  2. {  
  3.             int bal = 0;  
  4.              
  5.             BaseCommand cmdDeposit = CommandFactory.GetCommand("Deposit");  
  6.   
  7.             Transaction trans1 = new Transaction();  
  8.             trans1.Amount = 1000;  
  9.   
  10.             CommandInvoker invoker1 = new CommandInvoker(cmdDeposit);  
  11.   
  12.             bal = invoker1.ExecuteCommand(trans1);  
  13.   
  14.             Console.Write("Amount deposited. Your balance is: " + bal.ToString());  
  15.   
  16.             //------------------             
  17.   
  18.             BaseCommand cmdWithdraw = CommandFactory.GetCommand("Withdraw");  
  19.   
  20.             trans1.Amount = 400;  
  21.   
  22.             CommandInvoker invoker2 = new CommandInvoker(cmdWithdraw);  
  23.   
  24.             bal = invoker2.ExecuteCommand(trans1);  
  25.   
  26.             Console.Write("Amount withdrawn. Your balance is: " + bal.ToString());  
  27.   
  28.             // -- Undo withdraw  
  29.             bal = invoker2.UndoCommand();  
  30.   
  31.             Console.Write("Withdrawal Undone. Your balance is: " + bal.ToString());  
  32.   
  33.             Console.Read();  
  34.         }  
  35. }  
CommandFactory is just a utility class. This is not a part of Command Pattern.

  1. public static class CommandFactory  
  2. {  
  3.         public static BaseCommand GetCommand(String command)  
  4.         {  
  5.             switch (command)  
  6.             {  
  7.                 case "Deposit":  
  8.                     return new ConcreteCommandDeposit();  
  9.   
  10.                 case "Withdraw":  
  11.                     return new ConcreteCommandWithdraw();  
  12.                       
  13.                 default:  
  14.                     return null;  
  15.             }  
  16.   
  17.         }  
  18. }  

Summary

Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls without the need to know the owner of the method or the method parameters.

Reference:

 
  

Design Pattern : Iterator Pattern Implementation

Iterator pattern allows sequential access of elements with out exposing the inside code. Let’s understand what it means. Let’s say you have a collection of records which you want to browse sequentially and also maintain the current place which recordset is browsed, then the answer is iterator pattern. It’s the most common and unknowingly used pattern. Whenever you use a ‘foreach’ (It allows us to loop through a collection sequentially) loop you are already using iterator pattern to some extent.

Figure: - Iterator business logic

In figure ‘Iterator business logic’ we have the ‘clsIterator’ class which has collection of customer classes. So we have defined an array list inside the ‘clsIterator’ class and a ‘FillObjects’ method which loads the array list with data. The customer collection array list is private and customer data can be looked up by using the index of the array list. So we have public function like ‘getByIndex’ ( which can look up using a particular index) , ‘Prev’ ( Gets the previous customer in the collection , ‘Next’ (Gets the next customer in the collection), ‘getFirst’ ( Gets the first customer in the collection ) and ‘getLast’ ( Gets the last customer in the collection).

So the client is exposed only these functions. These functions take care of accessing the collection sequentially and also it remembers which index is accessed.

Below figures ‘Client Iterator Logic’ shows how the ‘ObjIterator’ object which is created from class ‘clsIterator’ is used to display next, previous, last, first and customer by index.


Figure: - Client Iterator logic

Reference:

Design Pattern : Mediator Pattern Implementation

Many a times in projects communication between components are complex. Due to this the logic between the components becomes very complex. Mediator pattern helps the objects to communicate in a disassociated manner, which leads to minimizing complexity.
Figure: - Mediator sample example

Let’s consider the figure ‘Mediator sample example’ which depicts a true scenario of the need of mediator pattern. It’s a very user-friendly user interface. It has three typical scenarios.
Scenario 1:- When a user writes in the text box it should enable the add and the clear button. In case there is nothing in the text box it should disable the add and the clear button.
Figure: - Scenario 1

Scenario 2:- When the user clicks on the add button the data should get entered in the list box. Once the data is entered in the list box it should clear the text box and disable the add and clear button.
Figure: - Scenario 2

Scenario 3:- If the user click the clear button it should clear the name text box and disable the add and clear button.
Figure: - Scenario 3

Now looking at the above scenarios for the UI we can conclude how complex the interaction will be in between these UI’s. Below figure ‘Complex interactions between components’ depicts the logical complexity.
Figure: - Complex interactions between components

Ok now let me give you a nice picture as shown below ‘Simplifying using mediator’. Rather than components communicating directly with each other if they communicate to centralized component like mediator and then mediator takes care of sending those messages to other components, logic will be neat and clean.
Figure: - Simplifying using mediator
Now let’s look at how the code will look. We will be using C# but you can easily replicate the thought to JAVA or any other language of your choice. Below figure ‘Mediator class’ shows the complete code overview of what the mediator class will look like.

The first thing the mediator class does is takes the references of the classes which have the complex communication. So here we have exposed three overloaded methods by name ‘Register’. ‘Register’ method takes the text box object and the button objects. The interaction scenarios are centralized in ‘ClickAddButton’,’TextChange’ and ‘ClickClearButton’ methods. These methods will take care of the enable and disable of UI components according to scenarios.
Figure: - Mediator class

The client logic is pretty neat and cool now. In the constructor we first register all the components with complex interactions with the mediator. Now for every scenario we just call the mediator methods. In short when there is a text change we can the ‘TextChange’ method of the mediator, when the user clicks add we call the ‘ClickAddButton’ and for clear click we call the ‘ClickClearButton’.
Figure: - Mediator client logic

Reference:
 

Thursday, February 16, 2012

Design Pattern : Chain of Responsibility pattern Implementation

Definition

GoF -> A way of passing a request between a chain of objects
  1. The Chain of Responsibility pattern works with a list of Handler objects that have limitations on the nature of the requests they can deal with. If a handler object cannot handle a request, it passes it on to the next handler object in the chain. At the end of the chain, there can be either default or exceptional behavior.
  2. The pattern chains the receiving objects together, and then passes any request messages from object to object until it reaches an object capable of handling the message.
  3. Chain of Responsibility simplifies object interconnections. Instead of senders and receivers maintaining references to all candidate receivers, each sender keeps a single reference to the head of the chain, and each receiver keeps a single reference to its immediate successor in the chain.
  4. Sometimes, the request object has to go through the chain objects mandatorily, like Http pipeline.
  5. Sometimes only through few handlers.
Design

Let us take an example; we are conducting a GK context. We have three teams to answer the questions. Each team will have 10000 ms to answer the questions, and team one has to start the each question. If team one didn't answer the question, it will be passed on to the next team.

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

UML Diagram

From GoF

chain1.gif

chain2.gif

Code

---------------- handler Base class ----------------------
public abstract class Handlerbase
    {
        public Handlerbase NextTeam { get; private set; }
        public ContextObject Question { get; private set; }
        public Handlerbase(Handlerbase nextHandler, ContextObject question)
        {
            NextTeam = nextHandler;
            Question = question;
        }

        public abstract void HandleRequest();
    }
    ---------------- queue object one ----------------------
public class TeamOne: Handlerbase
    {
        public TeamOne(Handlerbase nextHandler, ContextObject question) : base(nextHandler, question) { }
        public override void HandleRequest()
        {
            Console.WriteLine("Question : {0}", Question.Question.ToString());
            Console.WriteLine("*******************************************"));
            Console.WriteLine("Wating for team one to respond");
            Thread.Sleep(10000);
            Console.WriteLine("\t no response from team one.....");
            NextTeam.HandleRequest();
        }
    }
    ---------------- chain object two ----------------------
    public class TeamTwo : Handlerbase
    {
        public TeamTwo(Handlerbase nextHandler, ContextObject question) : base(nextHandler, question) { }
        public override void HandleRequest()
        {
            Console.WriteLine("Wating for team two to respond");
            Thread.Sleep(10000);
            Console.WriteLine("\t no response from team two.....");
            NextTeam.HandleRequest();
        }
    }
    ---------------- chain object tree ----------------------
    public class TeamThree : Handlerbase
    {
        public TeamThree(Handlerbase nextHandler, ContextObject question) : base(nextHandler, question) { }
        public override void HandleRequest()
        {
            Console.WriteLine("Wating for team three to respond");
            Thread.Sleep(10000);
            Console.WriteLine("\t no response from team three as well .....");
        }
    }
    ---------------- Request----------------------
    public class ContextObject
    {
        public string Question { get; set; }
    }
   ---------------- Client----------------------
        static void Main(string[] args)
        {
            ContextObject question = new ContextObject() { Question = "Who is an ediat in your team?" };
            TeamThree teamThree = new TeamThree(null, question);
            TeamTwo teamTwo = new TeamTwo(teamThree, question);
            TeamOne teamOne = new TeamOne(teamTwo, question);
            teamOne.HandleRequest();
            Console.ReadKey();
        }
  
Another Example:

To consider a more formal example, assume a scenario where you’ve a banking system, and you want to implement some kind of Loan approval. The customer may request a loan, and if it is below a specific amount, the cashier may  approve it directly. If it is above the specified amount, he might pass the request to his manager for approval.
So you may use Chain Of Responsibility implementation to hand over the request/command to the correct approver. For an example, consider this implementation of the above Bank account scenario. Our business rule is something like, a cashier can approve the request if the amount is lesser than 1000 $$, other wise the approval should be passed to the manager. The manager can approve the request if the amount is lesser than 10,000 $$.
We have the following components.
  • LoanRequest – A concrete request
  • IRequestHandler – Abstract request handler implementation
    • Concrete handlers like Cashier and Manager implements this
    • Has a reference to the successor to pass the request
  • Program – The main driver

To the code 

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

namespace DesignPatternsCof
{


    //Request
    class LoanRequest
    {
        public string Customer { get; set; }
        public decimal Amount { get; set; }
    }

    //Abstract Request Handler
    interface IRequestHandler
    {
        string Name { get; set; }
        void HandleRequest(LoanRequest req);
        IRequestHandler Successor { get; set; }
    }

    //Just an extension method for the passing the request
    static class RequestHandlerExtension
    {
        public static void TrySuccessor(this IRequestHandler current, LoanRequest req)
        {

            if (current.Successor != null)
            {
                Console.WriteLine("{0} Can't approve - Passing request to {1}", current.Name, current.Successor.Name);
                current.Successor.HandleRequest(req);
            }
            else
            {
                Console.WriteLine("Amount invaid, no approval given");               
            }
        }
    }

    //Concrete Request Handler - Cachier
    //Cachier can approve requests upto 1000$$
    class Cashier : IRequestHandler
    {
        public string Name { get; set; }
       
        public void HandleRequest(LoanRequest req)
        {
            Console.WriteLine("\n----\n{0} $$ Loan Requested by {1}",
                  req.Amount, req.Customer);

           if (req.Amount<1000)
               Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                    req.Amount,req.Customer, this.Name);
           else
               this.TrySuccessor(req);
        }

        public IRequestHandler Successor { get; set; }      
    }

    //Concrete Request Handler - Manager
    //Manager can approve requests upto 10000$
    class Manager : IRequestHandler
    {
        public string Name { get; set; }
        public void HandleRequest(LoanRequest req)
        {
            if (req.Amount < 10000)
                Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                         req.Amount, req.Customer, this.Name);
            else
               this.TrySuccessor(req);

        }
        public IRequestHandler Successor { get; set; } 
    }

  

    //Main driver
    class Program
    {
        static void Main(string[] args)
        {
            //Customers
            var request1 = new LoanRequest() { Amount = 800, Customer = "Jimmy"};
            var request2 = new LoanRequest() { Amount = 5000, Customer = "Ben"};
            var request3 = new LoanRequest() {Amount = 200000, Customer = "Harry"};

            //Approvers, chained together
            var manager = new Manager() {Name = "Tom, Manager"};
            var cashier = new Cashier(){ Name = "Job, Cachier", Successor = manager};

            //All customers request cashier first to approve
            cashier.HandleRequest(request1);
            cashier.HandleRequest(request2);
            cashier.HandleRequest(request3);

            Console.ReadLine();
        }


    }
} 
And this is what you’ll see upon execution.
image
So, you may observe that Loan Requests from different customers are passed to the cashier in the above example, and the cashier in his approve method passes the request to his successor (i.e, the manager) if the amount is higher than what he can approve. The implementation is pretty minimal, as you can see.
image
We actually  have an Abstract request handler implementation IReqeustHandler and two concrete request handlers, Cashier and Manager. Each request handler may hold a reference to the successor. You may see that we are setting the Successor of Cashier as Manager, so if the  amount requested his beyond a limit, the cashier may pass it to the manager for his approval.

Reference: