Sunday, 13 March 2022

Factory Design pattern

 # Factory Design Pattern

Define an interface for creating an object, but let sub-classes decide which class to instantiate.

## Factory Example

public interface IEmployeeManager
{
    decimal GetBonus();
    decimal GetPay();
}

### ContractEmployeeManager.cs

public class ContractEmployeeManager : IEmployeeManager
{
    public decimal GetBonus()
    {
        return 5;
    }

    public decimal GetPay()
    {
        return 12;
    }
}

### PermanentEmployeeManager.cs

public class PermanentEmployeeManager : IEmployeeManager
{
    public decimal GetBonus()
    {
        return 10;
    }

    public decimal GetPay()
    {
        return 8;
    }
}

### EmployeeManagerFactory.cs

public class EmployeeManagerFactory
{
    public IEmployeeManager GetEmployeeManager(int employeeTypeID)
    {
        IEmployeeManager returnValue = null;
        if (employeeTypeID == 1)
        {
            returnValue = new PermanentEmployeeManager();
        }
        else if (employeeTypeID == 2)
        {
            returnValue = new ContractEmployeeManager();
        }
        return returnValue;
    }
}

### How to use factory manager class

EmployeeManagerFactory empFactory = new EmployeeManagerFactory();
IEmployeeManager empManager = empFactory.GetEmployeeManager(employee.EmployeeTypeID);


No comments:

Post a Comment

Search This Blog

Creating your first "Alexa" Skill

Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...