Dependency chain resolution using IoC container

When you have a dependency between two modules, that modules are not well-separated with each other which are not good when design a large application that needs to be modularized and independent. IoC (Inversion of Control or Dependency Injection whatever), as name suggested, comes to rescue us and resolve the problem by injecting an external dependencies to our modules and using the container (that is injected) to decouple the dependencies between modules, so now the dependencies are inverted to our container and that container will control and manage the rest.

Ok, it sounds confusing. Let's me show you some examples..

 

So our solution from IoC pattern suggestion'd be:

 

But if we'd like to input some parameter such as connectionString (not only connectionString, also other inputs as you wish!), above figure example cannot solve this problem without create dependency between modules, and if there are chains of those dependencies that could be very bad.

Our hero is IoC container (provider), it can resolve the dependency chain problem by automatically calling the MemberPayment constructor method and support its parameter. We have to just tell them some information about those Concrete class that we want to instantiate without concerning about the dependencies between each module, that's amazing.

One of popular IoC containers is Castle Windsor, http://www.castleproject.org.

The code below demonstrates the use of Castle Windsor library to resolve the problem of Shop and MemberPayment in our previous examples but let's me explain more about my requirements. Since we're building a small shopping service that users come and pay money, we have to know who are our customers so that we can compute special prices for them. In another word, we need to connect with the MembershipProvider database that are far away (assumed).

//all these classes belong to theBlogFor namespace. interface IPaymentService { double CalculateTotalPrice(); } public class NonMemberPayment: IPaymentService { #region IPaymentService Members public double CalculateTotalPrice() { throw new NotImplementedException(); } #endregion } public class MemberPayment: IPaymentService { public string ConnectionString; public MemberPayment(string connectionString){ ConnectionString = connectionString; } #region IPaymentService Members public double CalculateTotalPrice() { throw new NotImplementedException(); } #endregion }

 

public class Shop { bool isMember = true; WindsorContainer container; public void BuyItems(/*...items...*/){ container = new WindsorContainer(new XmlInterpreter(new Castle.Core.Resource.ConfigResource("castle"))); if (isMember) { MemberPayment serviceForMember = container.Resolve<IPaymentService>("MemberPayment") as MemberPayment; System.Windows.Forms.MessageBox.Show(serviceForMember.ConnectionString); } else { NonMemberPayment serviceForNonMember = container.Resolve<IPaymentService>("NonMemberPayment") as NonMemberPayment; } } }

 The point is; container.Resolve<IPaymentService>("MemberPayment"), "MemberPayment" is an ID that you specified in XML config file (see it later). You may have a question how WindsorContainer knows my initial value of the connectionString for MemberPayment. That's because we describe the default parameter of connectionString in config file (that's all). In conclusion, when we call Resolve method, container'll look up the XML (since we tell them to do so by XmlInterpreter(...) ), then it'll know from that config file which components it has to instantiate and give those the parameters they require. After this process, we'll get IPaymentService obj, as expected, and finally the MessageBox'll be shown out with the connectionString message (sound boring..).

Not only you can specify the default connectionString in config file, you can also input the anonymous-type arguments as parameters too : container.Resolve<IPaymentService>("MemberPayment", new { connectionString = "ok! that 's enough, stop this lesson." }). 

container = new WindsorContainer(new XmlInterpreter(new Castle.Core.Resource.ConfigResource("castle"))); from this line, we tell WindsorContainer that there is some xml code that it has to concern when building a container as you can see :

<configuration> <configSections> <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,Castle.Windsor"/> </configSections> <castle> <components> <component id="NonMemberPayment" service="theBlogFor.IPaymentService,theBlogFor" type="theBlogFor.NonMemberPayment,theBlogFor"/> <component id="MemberPayment" service="theBlogFor.IPaymentService,theBlogFor" type="theBlogFor.MemberPayment,theBlogFor"> <parameters> <connectionString>Data Source=MYCOMNAME\SQLEXPRESS;Initial Catalog=theBlogForMembershipProvider;Integrated Security=True;Pooling=False</connectionString> </parameters> </component> </components> </castle> </configuration>

We support parameters for MemberPayment since it needs to identify database that keeps members, but for NonMemberPayment, it doesn't care about this at all. You can specify the parameters like above, or specify them inside the property for future use :

<properties> <connection>YourConnectionString</connection> </properties> <component id="xxx" service="yyy" type="zzz"> <parameters> <connectionString>#{connection}</connectionString> </parameters> </component>

Concept of IoC container is very pervasively used in real world app including in MVC that can be combined with ControllerFactory to create sophisticated Controller obj. Examples of MVC can be easily obtained on the Internet. Hope you get something from this article : - )


kick it on DotNetKicks.com     Shout it

Categories:   Design Patterns
Actions:   E-mail | del.icio.us | Permalink | Comments (3) | RSS


Make use of the Behavioral State Pattern

Hello my friend ,today I wanna try to write about state behavioral pattern that is used in many areas and cases. When implementing this pattern ,you expect the behavior of objects to be changed when their internal state changes ,for example ,when you move your mouse around (like now) ,your mouse behavior is different according to its current status. Like when you use PenTool or SelectionTool in a drawing program ,two classes for each tool can be created but it's a painful task when dealing with many many objects(tools in this place) ,don't you think? Because most actions(clicking ,dragging) of those tools still are not such a big different. You have mouse_Click() ,mouse_Drag() ,for example. So in this situation ,state pattern will be your choice.

I will illustrate the pattern with my example below ,this example is easy to understand(I think). If you have a better idea or have any questions ,you can leave a message. Also ,I'm not a game developer if I make you guy angry ,I'm so sorry..

This example scenario : I want to have a player of one game that can "Fire a weapon" and take an action "Jump" ,I'm not fill in irrelevant details about weapons ,actions ,or activities that will make my code complicated... The thing that is worth to look at is the state of the player. There are two states (or mode in this scenario) the "Normal" mode and the "Super Power" mode. For those two ,player can still jump and fire but the result damage will be different related to the player's state.I forgot to tell that another important point of this state pattern (actually it depends on the design but most of them) is when you implement it with on the fly loading or lazy loading. Don't mix up with lazy developer (like me). I'll show it to you later on in this article.

Firstly ,I want myself to easily write the code in main function like below ,as you can see that it's very readable. Especially ,when switching the player's state :

static void Main(string[] args)
        {
            Player player1 = new Player(1);
            //default player state is Normal state
            player1.FireWeapon(/*..*/);
            player1.Jump();

            player1.ChangePlayerState(new SuperPowerState());
            player1.FireWeapon(/*..*/);
            player1.Jump();
        }

Player has a field that can keep his state and he can fire weapon and jump... Notice this line of code  if (!playerState.IsStateInitialized)InitializePlayerState(); you can see it in every action because we want to perform lazy loading or load-on-fly ,say that if the PlayerState class isn't instantiated yet ,just do it! This instantiation doesn't cause from manually instantiation but from when we want to take some actions of the player (like FireWeapon() or Jump()).

class Player
    {
        private PlayerState playerState;
        public int PlayerID { get; set; }
        public Player(int ID)
        {
            //use default state
            playerState = new NormalState();
            PlayerID = ID;
        }

        public void InitializePlayerState()
        {
            playerState.InitializeState(this, PlayerID);
        }

        public void ChangePlayerState(PlayerState playerStateTobeChangedTo)
        {
            playerState = playerStateTobeChangedTo;
        }

        public void FireWeapon(/*necessary information e.g. weapon id ,etc.*/)
        {
            if (!playerState.IsStateInitialized)
                InitializePlayerState();

            double damage = playerState.FireWeapon(/*arguments*/);
            Console.WriteLine("Hit : " + damage+" points");

            //...send some messages to tell ,maybe ,the player director class 
            //to know that someone was hit with how much damage value for example...
        }

        public void Jump()
        {
            if (!playerState.IsStateInitialized)
                InitializePlayerState();

            int jumpHeight = playerState.Jump();
            Console.WriteLine("Jump : " + jumpHeight);

            //...take more actions...
        }
    }

We need the state base class that contains basic methods like ChangeState(...) and InitializeState(...) that will support Player class:

class PlayerState
    {
        public bool IsStateInitialized{ get; set; }

        public virtual void InitializeState(Player context, int playerID){}

        protected void ChangeState(Player player, PlayerState playerState)
        {
            player.ChangePlayerState(playerState);
        }

        public virtual double FireWeapon()
        {
            return 0;
        }

        public virtual int Jump()
        {
            return 0;
        }

    }

For "NormalState" and "SuperPowerState" class ,you can add more funtionalities or whatever you want but don't forget to call ChangeState(...) when you want player to initialize his new state.

class NormalState : PlayerState
    {
        private double damageMulplier;
        private int jumpHeight;

        public override void InitializeState(Player player, int playerID)
        {
            //...load necessary information of a player for 
            //this particular state from somewhere...
            damageMulplier = 10.0;  //assumed
            jumpHeight = 100;  //assumed

            Console.WriteLine("=> Player ID {0} mode is Normal.",playerID);

            //NormalState playerState = new NormalState();
            //ChangeState(player, playerState);

            IsStateInitialized = true;

            ChangeState(player, this);
        }

        public override double FireWeapon()
        {
            //...calculate the posibiliy of bullet hit the enemy...
            double hitRate = 0.6;   //assume the result

            return hitRate * damageMulplier;
        }

        public override int Jump()
        {
            return jumpHeight;
        }
    }

    class SuperPowerState : PlayerState
    {
        private double damageMulplier;
        private int jumpHeight;

        public override void InitializeState(Player player, int playerID)
        {
            //...load necessary information of a player for 
            //this particular state from somewhere...
            damageMulplier = 30.0;  //assumed
            jumpHeight = 300;  //assumed

            Console.WriteLine("=> Player ID {0} mode is SuperPower.", playerID);

            //SuperPowerState playerState = new SuperPowerState();
            //ChangeState(player, playerState);

            IsStateInitialized = true;

            ChangeState(player, this);
        }

        public override double FireWeapon()
        {
            //...calculate the posibiliy of bullet hit the enemy...
            double hitRate = 0.5;   //assume the result

            return hitRate * damageMulplier;
        }

        public override int Jump()
        {
            return jumpHeight;
        }
    }

Finally ,I'd like to refer to this UML class diagram of the State Design Pattern. We have State and Handle() which are PlayerState and PlayerState.FireWeapon() ,Context and Request() which are Player and his actions. Context has State and call state.Handle() that's like our Player has PlayerState as an instance field and call playerState.FireWeapon() that will call playerState.FireWeapon() accordingly.

Thanksss!!! kick it on DotNetKicks.com

Categories:   Design Patterns
Actions:   E-mail | del.icio.us | Permalink | Comments (4) | RSS


Observer Design Pattern Implementation

Long time no see... Today I'll create one simple example that uses Observer behavioral pattern of the GOF. Observer pattern is used when you want other objects to be notify when something happens with a particular object. For my example ,I want some parts of our company (may be just a little company :P) knows when stock items of our shop is lower than 10 pieces. If it is below 10 ,then alert the notifications for e.g. the transportation part and the warehouseing part to understand the problem. Our notification message has to be composed of : which part(transportation/warehouseing) we want to send to ,what the shop name ,location ,and type (that sends this notification) is. The code is not too hard too understand ,so I won't explain much in details.

Firstly ,we create the Shop class that holds some information about our shop :

public class Shop
    {
        //Shop ID discarded for simplicity
        public string Name { get; set; }
        public string Location { get; set; }
        private int _StockItemsCount;

        public event StockChanged StockChangedObsever;

        public Shop(string name, string location, int stockItemsCount)
        {
            Name = name;
            Location = location;
            _StockItemsCount = stockItemsCount;
        }

        public int StockItemsCount
        {
            get { return _StockItemsCount; }
            set
            {
                _StockItemsCount = value;

                if (_StockItemsCount < 10)
                    //alert that this inventory items number is too low ,need replenishment
                    this.StockChangedObsever(this);
            }
        }
    }

Delegate helps us make work easier ,it can be called back when we need :

 

public delegate void StockChanged(Shop shop);

 

We then build Observer base class and its derived classes (actually ,you don't need to do like this but I am showing you that there are two different parts in our company that will be notified) :

public class ObserverBase{
        protected virtual void OnStockChanged (Shop outOfStockShop)
        {
            Console.WriteLine("{0} has been run out of stock!!   \nShop type: {1}   Location: {2}", outOfStockShop.Name, outOfStockShop.GetType().ToString(), outOfStockShop.Location);
        }

        public void ObserverStockItems(Shop shop)
        {
            shop.StockChangedObsever += new StockChanged(OnStockChanged);
        }
    }

    public class InventoryObserver : ObserverBase
    {
        protected override void OnStockChanged(Shop outOfStockShop)
        {
            base.OnStockChanged(outOfStockShop);
            Console.WriteLine("=> Updating {0}'s stock items the warehouse...    \nShop type: {1}   Location: {2}\n" , outOfStockShop.Name, outOfStockShop.GetType().ToString(), outOfStockShop.Location);
            //perform an operation ...
        }
    }

    public class TransportationObserver : ObserverBase
    {
        protected override void OnStockChanged(Shop outOfStockShop)
        {
            base.OnStockChanged(outOfStockShop);
            Console.WriteLine("=> Transporting to {0}'s stock from the warehouse...    \nShop type: {1}   Location: {2}\n" , outOfStockShop.Name, outOfStockShop.GetType().ToString(), outOfStockShop.Location);
            //perform an operation ...
        }
    }

For the main class :

static void Main(string[] args)
        {
            Shop shop1 = new Shop("theBlogFor Magazine", "NY ,NewYork",50);
            Shop shop2 = new Shop("Suppy Souvenir", "BKK ,Bangkok", 20);

            //declare all of our observers
            InventoryObserver iObsr = new InventoryObserver();
            TransportationObserver tObsr = new TransportationObserver();

            iObsr.ObserverStockItems(shop1);
            tObsr.ObserverStockItems(shop1);
            iObsr.ObserverStockItems(shop2);
            tObsr.ObserverStockItems(shop2);

            shop1.StockItemsCount = 5;
            shop2.StockItemsCount = 8;
        }

 

Let's check this UML of GOF out. Observer class is obvious in our example code. We have two concrete observer classes that can have different observer states(the notification messages that were printed out) ,on the other hand ,we get some states(name, type ,location) from ConcreteSubject which is our Shop class. Our shop class can be attached with the observer via the event "StockChangedObsever" and delegate. Finally the Shop class can also be notified if something has been changed that is in our StockItemsCount's set property when  its items count is below ten.

Thanks for your attention! you can leave a comment...

kick it on DotNetKicks.com

Categories:   Design Patterns
Actions:   E-mail | del.icio.us | Permalink | Comments (12) | RSS


 

Tag Cloud