Fluent Builder Pattern

 
  • Creational pattern
  • Fluent Builder Pattern
  • without this pattern – it can happen that name can have middle name or not
  • With this pattern you get the flexibility to provide firstname/middlename/lastname
				
					

namespace builderPattern
{
    interface IEmployee
    {
        string FirstName { get; }
        string MiddleName { get; }
        string LastName { get; }
    }
    public class Employee : IEmployee
    {
        
        private string firstName;
        private string middleName;
        private string lastName;
        private Employee()
        {

        }

        public override string ToString()
        {
            return FirstName + " " + MiddleName + "" + LastName;
        }
        public string FirstName { get { return firstName; } }

        public string MiddleName => middleName;

        public string LastName => lastName;

        public class EmployeeBuilder
        {
            private readonly Employee _employee;
            public EmployeeBuilder()
            {
                _employee = new Employee();
            }
            public EmployeeBuilder WithFirstName(string firstName)
            {
                _employee.firstName = firstName;
                return this;
            }

            public EmployeeBuilder WithMiddleName(string middleName)
            {
                _employee.middleName = middleName;
                return this;
            }

            public EmployeeBuilder WithLastName(string lastName)
            {
                _employee.lastName = lastName;
                return this;
            }

            public Employee Build()
            {
                return _employee;
            }
        }
    }
}

				
			
				
					using static builderPattern.Employee;

var obj = new EmployeeBuilder().WithFirstName("Anurag").WithLastName("Nayak").Build();

Console.WriteLine(obj.ToString());

//you cannot create object of Employee class as its private
//Employee obj1 = new Employee();
				
			

Anurag Nayak

Leave a Comment