Last active
May 26, 2019 22:19
-
-
Save davidarobinson/d8cf236b634439124b5aa3394f37336d to your computer and use it in GitHub Desktop.
An example of the Builder Pattern, this file can be run in LinqPad. It is designed with a fluent interface, meaning that the methods return the builder and can be chained together. Objects can be created of different state to be used in unit test.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
Console.WriteLine(new PersonBuilder().WithValidDetails().Build()); | |
Console.WriteLine(new PersonBuilder().WithValidDetails().WithValidAddress().Build()); | |
} | |
public class Person{ | |
public string FirstName {get;set;} | |
public string LastName {get;set;} | |
public Address Address{get;set;} | |
} | |
public class Address{ | |
public string Address1{get;set;} | |
public string PostCode{get;set;} | |
public string Country{get;set;} | |
} | |
public class PersonBuilder | |
{ | |
private Person _person = new Person(); | |
public Person Build(){ | |
// Set standard default values for properties here if needed | |
return _person; | |
} | |
public PersonBuilder WithValidDetails() | |
{ | |
_person.FirstName="Joe"; | |
_person.LastName="Bloggs"; | |
return this; | |
} | |
public PersonBuilder WithValidAddress() | |
{ | |
_person.Address=new Address{ | |
Address1="1 The Grove", | |
PostCode="PembroVille", | |
Country="United Kingdom" | |
}; | |
return this; | |
} | |
public PersonBuilder WithInValidAddress() | |
{ | |
_person.Address=null; | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment