Sunday, August 19, 2018

Inversion of Control (IOC)

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



IOC:

IoC is a design principle which recommends the inversion of different kinds of controls in object-oriented design to achieve loose coupling between application classes.
In this case, control refers to any additional responsibilities a class has, other than its main responsibility, such as control over the flow of an application, or control over the dependent object creation and binding (Remember SRP - Single Responsibility Principle).
If you want to do TDD (Test Driven Development), then you must use the IoC principle, without which TDD is not possible.

"Don’t call us we will call you".

IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC. IOC is a concept where the flow of application is inverted. So for example rather than the caller calling the method.





Real life Example:

IoC is all about inverting the control. To explain this in layman's terms, suppose you drive a car to your work place.
This means you control the car. The IoC principle suggests to invert the control, meaning that instead of driving the car yourself, you hire a cab, where another person will drive the car.
Thus, this is called inversion of the control - from you to the cab driver. You don't have to drive a car yourself and you can let the driver do the driving so that you can focus on your main work.

The IoC principle helps in designing loosely coupled classes which make them testable, maintainable and extensible.

Example:

The above approach makes code more flexible as the caller is not aware of the object methods and the object is not aware of caller program flow.


          IOC:

  1. Service locator
  2. Events
  3. Delegates
  4. DI


  Types of DI:

  1. constructor DI
  2. Property DI
  3. Method DI




  Dependency Inversion Principle:

  The DIP principle also helps in achieving loose coupling between classes.
  It is highly recommended to use DIP and IoC together in order to achieve loose coupling.

          DIP suggests that high-level modules should not depend on low level modules. Both should depend on abstraction.












Saturday, August 18, 2018

Singleton Pattern

  1. Singleton pattern ensure that a class has only one instance and provides a global point of access on it
  2. A single constructor, that is private and parameterless
  3. The class is sealed.
  4. A static variable that holds a reference to the single created instance, if any.
  5. A public static means of getting the reference to the single created instance, creating one if necessary

Advantage:

Singleton pattern can be implemented interfaces.
It can be also inherit from other classes.
It can be lazy loaded.
It has Static Initialisation.
It can be extended into a factory pattern.
It helps to hide dependencies.

It provides a single point of access to a particular instance, so it is easy to maintain.

Dis Advantage:

1. Unit testing is more difficult (because it introduces a global state into an application).


2. This pattern reduces the potential for parallelism within a program, because to access the     singleton in a multi-threaded system, an object must be serialised (by locking).


Many way to implement singleton pattern in your code.

1. No Thread safe singleton

2. Thread Safe singleton

3. Thread safe singleton with double locking.

4. Thread safe singleton without using lock and no lazy initialisation.

5. fully lazy initialztion

6. Using .NET 4's Lazy<T> Type.


EXample:

class Program
    {
        static void Main(string[] args)
        {
            SampleA obj = SampleA.instance;
            Console.WriteLine("This is the First Message");

            SampleA obj1 = SampleA.instance;
            Console.WriteLine("This is the 2nd message");
            Console.ReadKey();

        }
    }

    //...............singleton Pattern
    //
    public  class SampleA
    {

        private SampleA()
        {
            counter++;
            Console.WriteLine("This is The Counter " + counter);
        }

        private static int counter = 0;
        public static SampleA Instance = null;
        public static SampleA instance
        {
            get
            {
                if (Instance== null)
                {
                    Instance = new SampleA();
                }
                return Instance;
            }

        }




    }





Different between Static class and singleton pattern in c#

  A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state.

While a static class allows only static methods and and you cannot pass static class as parameter. But singleton Do.


  1. Singleton Objects can dispose but not static class.
In short, single means single object across the application life cycle, so the scope is at application level. The static does not have any Object pointer, so the scope is at App Domain level.




  1. Singleton objects are stored in Heap, but static objects are stored in stack.
  2. We can clone (if the designer did not disallow it) the singleton object, but we can not clone the static class object .
  3. Singleton classes follow the OOP (object oriented principles), static classes do not.
  4. We can implement an interface with a Singleton class, but a class's static methods (or e.g. a C# static class) cannot.



Dirty Reads:

A dirty read occurs when two operations, like read and write both occurs at the same time and gives the incorrect or unedited data.



Real life use of Singleton pattern:


======================================================
Hi, We used the singleton pattern in our utility layers which consist of Logging, Caching, Service host repositories, Load Balancer...

 If the question is on how we arrived to the design. There was a performance lag on the utility layer eg, Logging, on diagnosing we observed that there are several instance getting created which are not required in my case. So we adopted Singleton pattern. Hope this helps

============================================================================

When you want only one instance of a class, you use singleton classes.

Eg- In a e-commerce website, you need only one shopping cart for a user. This is when you will choose shoppingcart class to be singleton.

So the user will use the same cart to buy men’s shirts, kids toys and cosmetics.

------------------------------

Singleton is like a single resource which is being shared among multiple users; for example - sharing a single washing machine among all the residents in a hotel or sharing a single appliance like refrigerator among all the family members.

Using a single instance of a class across your application requires a singleton class.









Dependency Injection (DI)


  1. DI is a software design pattern that is allow to develop loosely couple code.
  2. It is great way to reduce tightly coupling between software component.
  3. DI also enables us to manage future changes of code.
  4. The purpose of DI is make code maintainable.
 We have following different way to implement DI.

1. Constructor Injection.

2. Property/Setter Injection

3. Method Injection


1. Constructor Injection:

This is the widely way used way to implement DI.
Injected component can we used anywhere in the class.

Example:

class Program
    {
        static void Main(string[] args)
        {
            SampleA obj1 = new SampleA();
            Client C1 = new Client(obj1);
            C1.MethodShow();
            Console.ReadKey();
        }
    }

    public interface Isample
    {
        void Test();
    }

    public class Client
    {
        private Isample _sampleA;
        public Client(Isample sample)
        {
            _sampleA = sample;
        }

        public void MethodShow()
        {
            _sampleA.Test();
        }

    }

    public class SampleA:Isample
    {
        public void Test() {
            Console.WriteLine("This is Example of SampleA");
        }
    }

    public class SampleB:Isample
    {
        public void Test() {
            Console.WriteLine("This is Example of SampleA");
        }

    }


Property/Setter Injection:


class Program
    {
        static void Main(string[] args)
        {
            SampleA obj1 = new SampleA();
            Client c1 = new Client();
            c1.SampleA = obj1; // Pass Dependency
         
            Console.ReadKey();

        }
    }

    public interface Isample
    {
        void Test();
    }

    public class Client
    {
        private Isample _sampleA;

        public Isample SampleA 
        {
            set { _sampleA = value; }
        }

        public void MethodShow()
        {
            _sampleA.Test();
        }
    }

    public class SampleA : Isample
    {
        public void Test()
        {
            Console.WriteLine("This is Example of SampleA");
        }
    }

    public class SampleB : Isample
    {
        public void Test()
        {
            Console.WriteLine("This is Example of SampleA");
        }

    }

Method Injection:

Example:

static void Main(string[] args)
        {
            SampleA s1 = new SampleA();
            Client c1 = new Client();
            c1.start(s1);// pass dependency
            Console.ReadKey();
        }
    }

    public interface Isample
    {
        void Test();
    }

    public class Client
    {
        private Isample _sample;
        public void start(Isample s) {
            s.Test();
        }

    }

    public class SampleA : Isample
    {
        public void Test()
        {
            Console.WriteLine("This is Example of SampleA");
        }
    }

    public class SampleB : Isample
    {
        public void Test()
        {
            Console.WriteLine("This is Example of SampleA");
        }

    }



example:






For example, Suppose your Client class needs to use two service classes, then the best you can do is to make your Client class aware of abstraction i.e. IService interface rather than implementation i.e. Service1 and Service2 classes. In this way, you can change the implementation of the IService interface at any time (and for how many times you want) without changing the client class code.



Note:

Implement this method in SchoolBusinessLayer.cs. This method gets data from DataAccessLayer.

For this, in Constructor of SchoolBusinessLayer,  inject ISchoolDataAccessLayer.
Hence, we are not directly dependent upon SchoolDataAccessLayer.cs (This technique is used to make an Application Loosely Couple).


Throughout the project development, we never created any object. We communicated with one layer and another with the help of an interface.