Skip to content

Instantly share code, notes, and snippets.

@AndyStewart
Last active October 5, 2016 13:11
Show Gist options
  • Save AndyStewart/830a93d2f8c52d7e306d to your computer and use it in GitHub Desktop.
Save AndyStewart/830a93d2f8c52d7e306d to your computer and use it in GitHub Desktop.
Builder Pattern
public class Contact
{
public Contact(string firstname, string surname, string address)
{
this.Firstname = firstname;
this.Surname = surname;
this.Address = address;
}
public string Firstname { get; private set; }
public string Surname { get; private set; }
public string Address { get; private set; }
}
public class ContactBuilder
{
private string _firstname = "Default Firstname";
private string _surname = "Default Surname";
private string _address = "Default address";
public ContactBuilder WithFirstname(string firstname)
{
this._firstname = firstname;
return this;
}
public ContactBuilder WithSurname(string surname)
{
this._surname = surname;
return this;
}
public ContactBuilder WithAddress(string address)
{
this._address = address;
return this;
}
public Contact Build()
{
return new Contact(_firstname,_surname,_address);
}
}
public class SomeTests
{
[Fact]
public void TestShouldStuff()
{
var newContactWithAllPropertiesSet = new ContactBuilder()
.WithFirstname("Andrew")
.WithSurname("Stewart")
.WithAddress("My Nice House")
.Build();
var newContactWithOnePropertySetTheRestDefaults = new ContactBuilder()
.WithFirstname("Andrew")
.Build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment