Pipeline is a behavioral design pattern that allows you to process a series of data through a sequence of processing stages, where each stage can modify the data or make decisions based on it.
You can think of it as a series of steps that data goes through, where each step can transform the data or make decisions based on it.
Use Case
When you have a series of processing steps that need to be applied to data, and you want to decouple the steps from each other.
When you want to be able to easily add, remove, or reorder processing steps without affecting the rest of the system.
Code
Assume we are building loan management system.
We have a loan application that needs to go through multiple stages of processing before it can be approved or rejected.
Each stage of processing can be represented as a separate component in the pipeline.
//Class to store loan application detailspublicclassLoanApplication{publicintId{get;set;}publicintAge{get;set;}publicdecimalIncome{get;set;}publicdecimalLoanAmount{get;set;}publicstringCountry{get;set;}}//Class to store the decision of the loan applicationpublicclassLoadDecision{publicintApplicantId{get;set;}publicboolIsApproved{get;set;}publicstringRejectionReason{get;set;}publicoverridestringToString(){return$"ApplicantId: {ApplicantId}, IsApproved: {IsApproved}, RejectionReason: {RejectionReason}";}}
//Class to store the context of the loan application processingpublicsealedclassEligibilityContext{publicLoanApplicationLoanApplication{get;set;}publicList<string>Warning{get;set;}=newList<string>();publicboolIsRejected{get;set;}publicstringRejectionReason{get;set;}publicvoidReject(stringreason){IsRejected=true;RejectionReason=reason;}publicvoidWarn(stringreason){Warning.Add(reason);}}
//Interface for the eligibility rulespublicinterfaceIEligibilityRule{intOrder{get;}voidEvaluate(EligibilityContextcontext);}publicsealedclassAgeRule:IEligibilityRule{publicintOrder=>1;publicvoidEvaluate(EligibilityContextcontext){if(context.LoanApplication.Age<18){context.Reject("Applicant must be at least 18 years old.");}}}publicsealedclassIncomeRule:IEligibilityRule{publicintOrder=>2;publicvoidEvaluate(EligibilityContextcontext){if(context.LoanApplication.Income<20000){context.Reject("Applicant must have an income of at least $20,000.");}}}publicsealedclassLoanAmountRule:IEligibilityRule{publicintOrder=>3;publicvoidEvaluate(EligibilityContextcontext){if(context.LoanApplication.LoanAmount>context.LoanApplication.Income*5){context.Reject("Loan amount cannot exceed 5 times the applicant's income.");}}}publicsealedclassCountryRule:IEligibilityRule{publicintOrder=>4;privatereadonlyHashSet<string>_allowedCountries=newHashSet<string>{"USA","Canada","UK"};publicvoidEvaluate(EligibilityContextcontext){if(!_allowedCountries.Contains(context.LoanApplication.Country)){context.Reject($"Applicants from {context.LoanApplication.Country} are not eligible.");}}}