Builder: Implementation and Example
Learn the Builder design pattern by implementing an example program.
In our example, we’ll once again build an audio player that can play audio on both Linux and Windows operating systems, as we did for Factory Method and Abstract Factory. This time, we’ll do so by using the Builder design pattern.
Creating a console application
We’ll start by creating a .NET console application. We’ll first add some static utility classes that’ll provide audio playback functionality on both Windows and Linux.
Implementing the utility classes
For the Linux implementation, we’ll add the LinuxPlayerUtility.cs
file with the following content:
Press + to interact
using System.Diagnostics;namespace Builder_Demo;internal static class LinuxPlayerUtility{public static Process? PlaybackProcess { get; set; }public static void StartBashProcess(string command){var escapedArgs = command.Replace("\"", "\\\"");var process = new Process(){StartInfo = new ProcessStartInfo{FileName = "/bin/bash",Arguments = $"-c \"{escapedArgs}\"",RedirectStandardOutput = true,RedirectStandardInput = true,UseShellExecute = false,CreateNoWindow = true,}};process.Start();}}
Windows implementation will be placed into the WindowsPlayerUtility.cs
file, which will contain the following code:
Press + to interact
using System.Runtime.InteropServices;using System.Text;namespace Builder_Demo;internal static class WindowsPlayerUtility{[DllImport("winmm.dll")]private static extern int mciSendString(string command,StringBuilder stringReturn,int returnLength,IntPtr hwndCallback);public static void ExecuteMciCommand(string commandString){var sb = new StringBuilder();var result = mciSendString(commandString, sb, 1024*1024,IntPtr.Zero);Console.WriteLine(result);}}
Implementing the “Play” button
We’ll then add the PlayButton.cs
...