C# Design Patterns in Unity3D : Strategy Pattern


Strategy Pattern

I will try to explain this pattern as simple as I can because it is really simple and useful. Lets define  a problem: Think about that you have employees in different departments with different titles and you need a method which calculates different salaries.

Answer 1 – You can write a method which takes the jobType parameter and you can calculate different salaries with one method. The main disadvantage of this way is that the main class must know all parameters. Also it’s hard to add new job type – you need to add new parameters and methods into the class.

Answer 2 – You can use inheritence. Create an Employee class and extend it with the other employee type classes. Each of them has its own method so you do’nt need any parameter. But what if you want to add a new method to calculate holidays of different departments? For this answer, you must create another employee class and its subclasses because each employee belongs the same department in this solution.

Answer 3- USE STRATEGY PATTERN! In this solution, create an employee class and two more classes which extend this class: Salary class and Holidays class. Salary class is implemented by job type classes and holidays class is implemented by departments. Lets give a try.

These two interfaces give us methods which will be used in classes.

Now, we can create Employee class.

Finally, we can create our objects and call their methods in Main class.

In this part, you have 3 different employee types in different departments. You can also use int values separately. You can see class diagram of this example.

strategy

 

 

©Coffee Break Codes – C# Design Patterns in Unity3D : Strategy Pattern


Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “C# Design Patterns in Unity3D : Strategy Pattern

  • Hadi GHasemiZadeh

    Hi,

    Thank you for your great topic. I think it is better, for sake of encapsulation in Employee class use:
    private ISalary salary;
    private IHolidays holidays;

    and in MainClass you must change it to :
    Employee employee1 = new Employee(new EmlpoyeeASalary(), new DepartmentAHolidays());
    int salaryA = employee1.CalcSalary();
    int holidayA = employee1.CalcHolidays();

    Employee employee2 = new Employee(new EmlpoyeeBSalary(), new DepartmentAHolidays());
    int salaryB = employee2.CalcSalary();
    int holidayB = employee2.CalcHolidays();

    Employee employee3 = new Employee(new EmlpoyeeCSalary(), new DepartmentBHolidays());
    int salaryC = employee3.CalcSalary();
    int holidayC = employee3.CalcHolidays();