Skip to content

Instantly share code, notes, and snippets.

@imzjy
Created April 18, 2020 03:48
Show Gist options
  • Save imzjy/42a00679d3b8d674c5879e1de5481fb4 to your computer and use it in GitHub Desktop.
Save imzjy/42a00679d3b8d674c5879e1de5481fb4 to your computer and use it in GitHub Desktop.
using System;
namespace Zjy.Utils
{
public class Car {
public string Make {get; set;}
public string Model {get; set;}
public string Year {get; set;}
public int Mileage {get; set;}
public decimal Price {get; set;}
public void Save() {
Console.WriteLine("Saved!");
}
public override string ToString() {
return $"{Make} {Year} with mileage {Mileage} at Price: ${Price}";
}
}
# region Builder Pattern
public interface ICarBuilder
{
Car Car { get; }
Car Build();
}
public class CarBuilder : ICarBuilder
{
private Car _car = null;
public CarBuilder()
{
_car = new Car();
}
public Car Car => this._car;
public Car Build()
{
this._car.Save();
return this._car;
}
}
# endregion
# region Extension Methods
/// <summary>
/// We can add customized extensions to ICarBuilder.
/// Even if we shipped following piece of code.
/// </summary>
public static class CarBuilderExtentions
{
public static ICarBuilder AddPrice(this ICarBuilder builder, decimal price)
{
builder.Car.Price = price;
return builder;
}
public static ICarBuilder AddMileage(this ICarBuilder builder, int mileage)
{
builder.Car.Mileage = mileage;
return builder;
}
public static ICarBuilder AddYear(this ICarBuilder builder, string year)
{
builder.Car.Year = year;
return builder;
}
public static ICarBuilder AddMake(this ICarBuilder builder, string make)
{
builder.Car.Make = make;
return builder;
}
}
# endregion
# region Usage
public class Program {
public static void Main(string[] args) {
var car = new CarBuilder()
.AddMake("Honda")
.AddYear("2020")
.AddMileage(20000)
.AddPrice(10000m)
.Build();
Console.WriteLine(car);
}
}
# endregion
}
Saved!
Honda 2020 with mileage 20000 at Price: $10000
{
"version": 1,
"target": "Run",
"mode": "Debug"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment