Dependency Injection Principal (DIP)

Dependency injection Principal ensures it should be more and perfect abstraction between base level & derived level implementation. Dependency inversion principle is to decouple application glue code from application logic. Reusing low-level components (application logic) becomes easier and maintainability is increased.        

 The below example is all about Project management in normal it field. Based on requirement we will add junior developers and senior developers.Here the manager manage only one junior developer & one senior developer .In future s/he needs to add one more junior then it is easy to create a new collection of developers with IEngineer.
/// <summary>
    /// Interface for Developer people
    /// </summary>
    public interface IEngineer
    {
        void Dowork();
    }
    /// <summary>
    /// Interface for Mentoring people
    /// </summary>
    public interface IMentor
    {
        void DoMentoring();
    }
 
    /// <summary>
    /// Class implementing Developer qualities
    /// </summary>
    public class SoftwareEngineer : IEngineer
    {
        public string Name { get; set; }
 
        public void Dowork()
        {
            Console.WriteLine(Name + " Doing Coding....");
        }
    }
    /// <summary>
    /// Class implementing Developer & Mentor Qualities
    /// </summary>
    public class SeniorSoftwareEngineer : IEngineer, IMentor
    {
        public string Name { get; set; }
 
        public void DoMentoring()
        {
            Console.WriteLine(Name +  " Mentoring Juniors...");
        }
 
        public void Dowork()
        {
            Console.WriteLine(Name +  " Doing Coding....");
        }
    }
    /// <summary>
    /// Manager class for Managing .With the implementation of Developers & Mentors
    /// </summary>
    public class Manager
    {
        IEngineer Developers;
        IMentor Mentors;
 
        public void SetWorker(IEngineer developer)
        {
            Developers = developer;
        }
 
        public void SetMenter(IMentor mentor)
        {
            Mentors = mentor;
        }
 
        public void Manage()
        {
            if(Developers !=null)
            Developers.Dowork();
 
            if(Mentors !=null)
            Mentors.DoMentoring();
        }
    }
 
Call
Manager manager = new Manager();
SoftwareEngineer Sharan = new SoftwareEngineer { Name = "Sharan" };
SeniorSoftwareEngineer Jannet = new SeniorSoftwareEngineer { Name = "Jannet" };
 
            manager.SetWorker(Sharan);
            manager.Manage();
 
            manager.SetWorker(Jannet);
            manager.SetMenter(Jannet);
            manager.Manage();
 
dd                                                                                            

No comments:

Post a Comment