Last active
March 7, 2018 15:33
-
-
Save dijeferson/38d7d426bf5ab72048af7eb5dbc2cd14 to your computer and use it in GitHub Desktop.
Simple sample of a Builder Design Pattern implementation in C#
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
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
namespace Builder | |
{ | |
public class Url | |
{ | |
private string basePath = string.Empty; | |
private Dictionary<string, string> parameters = new Dictionary<string, string>(); | |
public Url(string basePath, Dictionary<string, string> parameters) | |
{ | |
this.basePath = basePath; | |
this.parameters = parameters; | |
} | |
public override string ToString() | |
{ | |
var keyvalues = string.Empty; | |
foreach(var item in this.parameters) | |
keyvalues += item.Key + "=" + item.Value + "&"; | |
return this.basePath + keyvalues; | |
} | |
} | |
public interface IUrlBuilder | |
{ | |
IUrlBuilder WithBasePath(string input); | |
IUrlBuilder WithParameter(string key, String value); | |
Url Build(); | |
} | |
public class UrlBuilder : IUrlBuilder | |
{ | |
private string basePath = string.Empty; | |
private Dictionary<string, string> parameters = new Dictionary<string, string>(); | |
public IUrlBuilder WithBasePath(String input) | |
{ | |
this.basePath = input; | |
return this; | |
} | |
public IUrlBuilder WithParameter(String key, String value) | |
{ | |
if (!this.parameters.ContainsKey(key)) | |
this.parameters.Add(key, value); | |
return this; | |
} | |
public Url Build() | |
{ | |
return new Url(this.basePath, this.parameters); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var result = new UrlBuilder().WithBasePath("http://google.com/") | |
.WithParameter("q", "term") | |
.WithParameter("user", "batatinha") | |
.WithParameter("pwd", "123") | |
.WithParameter("source", "direct") | |
.Build(); | |
Console.WriteLine("******************************************"); | |
Console.WriteLine(result.ToString()); | |
Console.WriteLine("******************************************"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment