I have created a simple project using the Builder design pattern but I would like to add one more, maybe integrate the Singleton patterN. I am very new to design patterns, so I'm sorry if this question sounds a bit stupid. I will like to experiment with combining design patterns but I'm not sure what would fit the already existing project.
namespace BuilderProiect
{
class Program
{
static void Main(string[] args)
{
var builder = new EmployeeTestBuilder();
var employee = builder
.WithName("John")
.HasAge(23)
.HasGrossSalaryOf(2800)
.Build();
int actual = (int)employee.CalculateNetSalary();
Console.WriteLine("The name of the employee {0} who was born in {1} with gross salary {2} which is actual salary of {3}\n", employee.Name, employee.BirthDate, employee.GrossSalary, actual);
}
}
public class Employee
{
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public double GrossSalary { get; set; }
public double CalculateNetSalary()
{
var age = DateTime.Now.Year - BirthDate.Year;
if (age < 18)
throw new InvalidOperationException("Age less than 18");
if (age >= 18 && age < 30)
return GrossSalary * 0.8;
else
return GrossSalary * 0.85;
}
public class EmployeeTestBuilder
{
private Employee _employee;
public EmployeeTestBuilder()
{
_employee = new Employee();
}
/* public EmployeeTestBuilder Default()
{
_employee.Name = "Mark";
_employee.BirthDate = new DateTime();
_employee.GrossSalary = 1000;
return this;
}*/
public EmployeeTestBuilder WithName(string name)
{
_employee.Name = name;
return this;
}
public EmployeeTestBuilder HasAge(int age)
{
_employee.BirthDate = new DateTime(DateTime.Now.Year - age, DateTime.Now.Month, DateTime.Now.Day);
return this;
}
public EmployeeTestBuilder HasGrossSalaryOf(double salary)
{
_employee.GrossSalary = salary;
return this;
}
public Employee Build()
{
return _employee;
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire