├── .gitignore ├── AdapterPattern.Demo ├── AdapterPattern.Demo.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── WeatherAsCsvAdapter.cs ├── WeatherAsStringAdapter.cs ├── WeatherForecastProvider.cs ├── appsettings.Development.json └── appsettings.json ├── BridgePattern.Demo ├── BridgePattern.Demo.csproj ├── NotificationProcessor.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings.Development.json └── appsettings.json ├── BuilderPattern.Demo ├── BuilderPattern.Demo.csproj ├── Controllers │ └── WeatherForecastController.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── User.cs ├── WeatherForecast.cs ├── appsettings.Development.json └── appsettings.json ├── ChainOfResponsibility.Demo ├── ChainOfResponsibility.Demo.csproj ├── Program.cs └── SeniorManager.cs ├── CommandPattern.Demo ├── Command.cs ├── CommandPattern.Demo.csproj ├── IOrchestrator.cs ├── Orchestrator.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── Proxy.cs ├── appsettings.Development.json └── appsettings.json ├── CompositePattern.Demo ├── CompositeNode.cs ├── CompositePattern.Demo.csproj ├── LeafNode.cs ├── Node.cs └── Program.cs ├── DecoratorPattern.Demo ├── CakeMessageDecorator.cs ├── ChocolateCake.cs ├── DecoratorPattern.Demo.csproj ├── ICake.cs ├── ICakeMessageDecorator.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── VanillaCake.cs ├── appsettings.Development.json └── appsettings.json ├── FacadePattern.Demo └── FacadePattern.Demo │ ├── FacadePattern.Demo.sln │ └── FacadePattern.Demo │ ├── Business.cs │ ├── Controllers │ ├── InventoryController.cs │ ├── NotificationController.cs │ ├── PaymentController.cs │ └── PurchaseFacadeController.cs │ ├── FacadePattern.Demo.csproj │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── appsettings.Development.json │ └── appsettings.json ├── FactoryMethodPattern.Demo ├── Controllers │ ├── LawnmowerCatalogController.cs │ └── WeatherForecastController.cs ├── FactoryMethodPattern.Demo.csproj ├── ILawnmowerCatalog.cs ├── ILawnmowerCatalogAbstractFactory.cs ├── ILawnmowerCatalogFactory.cs ├── Lawnmower.cs ├── LawnmowerCatalogFactory.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── WeatherForecast.cs ├── appsettings.Development.json └── appsettings.json ├── FlyweightPattern.Demo └── FlyweightPattern.Demo │ ├── FlyweightPattern.Demo.sln │ └── FlyweightPattern.Demo │ ├── AudiCar.cs │ ├── BmwCar.cs │ ├── CarFactroy.cs │ ├── CarManager.cs │ ├── Controllers │ └── WeatherForecastController.cs │ ├── FlyweightPattern.Demo.csproj │ ├── ICar.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── appsettings.Development.json │ └── appsettings.json ├── InterpreterPattern.Demo ├── Context.cs ├── Expression.cs ├── Interpreter.cs ├── InterpreterPattern.Demo.csproj └── Program.cs ├── Iterator.Demo ├── Aggregate.cs ├── Iterator.Demo.csproj ├── Iterator.cs └── Program.cs ├── MediatorPattern.Demo ├── Cab.cs ├── CabCallCenter.cs ├── MediatorPattern.Demo.csproj ├── Passenger.cs └── Program.cs ├── MementoPattern.Demo ├── Employee.cs ├── EmployeeManager.cs ├── MementoPattern.Demo.csproj └── Program.cs ├── ObserverPattern.Demo ├── Observer.cs ├── ObserverPattern.Demo.csproj ├── Program.cs ├── Subject.cs └── User.cs ├── Pattern.Demo.sln ├── PrototypePattern.Demo ├── Controllers │ └── UserController.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── PrototypePattern.Demo.csproj ├── User.cs ├── appsettings.Development.json └── appsettings.json ├── ProxyPattern.Demo ├── ProxyPattern.Demo.sln ├── ProxyPattern.Demo │ ├── Controllers │ │ └── WeatherForecastController.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── ProxyPattern.Demo.csproj │ ├── WeatherProviderProxy.cs │ ├── appsettings.Development.json │ └── appsettings.json └── Weather.Forecast │ ├── IWeatherProvider.cs │ ├── Weather.Forecast.csproj │ ├── WeatherForecast.cs │ └── WeatherProvider.cs ├── README.md ├── StatePattern.Demo ├── StatePattern.Demo.sln └── StatePattern.Demo │ ├── Car.cs │ ├── Program.cs │ └── StatePattern.Demo.csproj ├── StrategyPattern.Demo ├── BubbleSort.cs ├── Program.cs ├── Sort.cs ├── SortedNumbers.cs └── StrategyPattern.Demo.csproj ├── TemplateMethodPattern.Demo ├── Program.cs ├── SOLID │ ├── Cart.cs │ ├── IItemValidator.cs │ ├── IPaymentExecutor.cs │ └── IReceiptSender.cs ├── TemplateMethod │ ├── Cart.cs │ └── EmailCart.cs └── TemplateMethodPattern.Demo.csproj └── VisitorPattern.Demo ├── INotificationSender.cs ├── IVisitor.cs ├── InvoiceNotificationSender.cs ├── MarketingNotificationSender.cs ├── Program.cs └── VisitorPattern.Demo.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /AdapterPattern.Demo/AdapterPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /AdapterPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using AdapterPattern.Demo; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | // Add services to the container. 7 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 8 | builder.Services.AddEndpointsApiExplorer(); 9 | builder.Services.AddSwaggerGen(); 10 | 11 | builder.Services.AddSingleton(); 12 | builder.Services.AddSingleton(); 13 | builder.Services.AddSingleton(); 14 | 15 | var app = builder.Build(); 16 | 17 | // Configure the HTTP request pipeline. 18 | if (app.Environment.IsDevelopment()) 19 | { 20 | app.UseSwagger(); 21 | app.UseSwaggerUI(); 22 | } 23 | 24 | app.UseHttpsRedirection(); 25 | 26 | app.MapGet("/weatherforecast", ([FromServices] IWeatherAsCsvAdapter weatherAsCsvAdapter) => 27 | weatherAsCsvAdapter.Get()) 28 | .WithName("GetWeatherForecast"); 29 | 30 | app.Run(); -------------------------------------------------------------------------------- /AdapterPattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:17970", 8 | "sslPort": 44326 9 | } 10 | }, 11 | "profiles": { 12 | "AdapterPattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7078;http://localhost:5078", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /AdapterPattern.Demo/WeatherAsCsvAdapter.cs: -------------------------------------------------------------------------------- 1 | using Csv; 2 | 3 | namespace AdapterPattern.Demo; 4 | internal interface IWeatherAsCsvAdapter 5 | { 6 | string Get(); 7 | } 8 | 9 | internal class WeatherAsCsvAdapter : IWeatherAsCsvAdapter 10 | { 11 | private readonly IWeatherForecastProvider weatherForecastProvider; 12 | 13 | public WeatherAsCsvAdapter(IWeatherForecastProvider weatherForecastProvider) 14 | { 15 | this.weatherForecastProvider = weatherForecastProvider; 16 | } 17 | 18 | public string Get() 19 | { 20 | var headers = new[] { "Date", "Temp", "Summary" }; 21 | var csv = weatherForecastProvider.Get().Select(w => new string[] { w.Date.ToString(), w.TemperatureF.ToString(), w.Summary }); 22 | return CsvWriter.WriteToText(headers, csv); 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /AdapterPattern.Demo/WeatherAsStringAdapter.cs: -------------------------------------------------------------------------------- 1 | namespace AdapterPattern.Demo; 2 | 3 | internal interface IWeatherAsStringAdapter 4 | { 5 | string Get(); 6 | } 7 | 8 | internal class WeatherAsStringAdapter : IWeatherAsStringAdapter 9 | { 10 | private readonly IWeatherForecastProvider weatherForecastProvider; 11 | 12 | public WeatherAsStringAdapter(IWeatherForecastProvider weatherForecastProvider) 13 | { 14 | this.weatherForecastProvider = weatherForecastProvider; 15 | } 16 | 17 | public string Get() 18 | { 19 | return string.Join( 20 | Environment.NewLine, 21 | weatherForecastProvider.Get().Select(w => $"{w.Date}|{w.TemperatureF}|{w.Summary}")); 22 | } 23 | } -------------------------------------------------------------------------------- /AdapterPattern.Demo/WeatherForecastProvider.cs: -------------------------------------------------------------------------------- 1 | namespace AdapterPattern.Demo; 2 | 3 | internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary) 4 | { 5 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 6 | } 7 | 8 | internal interface IWeatherForecastProvider 9 | { 10 | IEnumerable Get(); 11 | } 12 | 13 | internal class WeatherForecastProvider : IWeatherForecastProvider 14 | { 15 | string[] summaries = new[] 16 | { 17 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 18 | }; 19 | 20 | public IEnumerable Get() 21 | { 22 | var forecast = Enumerable.Range(1, 5).Select(index => 23 | new WeatherForecast 24 | ( 25 | DateTime.Now.AddDays(index), 26 | Random.Shared.Next(-20, 55), 27 | summaries[Random.Shared.Next(summaries.Length)] 28 | )) 29 | .ToArray(); 30 | return forecast; 31 | } 32 | } -------------------------------------------------------------------------------- /AdapterPattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /AdapterPattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /BridgePattern.Demo/BridgePattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /BridgePattern.Demo/NotificationProcessor.cs: -------------------------------------------------------------------------------- 1 | namespace BridgePattern.Demo; 2 | public interface INotificationProcessor 3 | { 4 | void ProcessNotification(string message); 5 | } 6 | 7 | public class TextNotificationProcessor : INotificationProcessor 8 | { 9 | private readonly INotificationSender notificationSender; 10 | 11 | public TextNotificationProcessor(INotificationSender notificationSender) 12 | { 13 | this.notificationSender = notificationSender; 14 | } 15 | public void ProcessNotification(string message) 16 | { 17 | notificationSender.SendNotification(message); 18 | } 19 | } 20 | 21 | public interface INotificationSender 22 | { 23 | void SendNotification(string message); 24 | } 25 | 26 | public class TextNotificationSender : INotificationSender 27 | { 28 | public void SendNotification(string message) 29 | { 30 | Console.WriteLine($"Text: {message}"); 31 | } 32 | } 33 | 34 | public class EmailNotificationProcessor : INotificationProcessor 35 | { 36 | private readonly INotificationSender notificationSender; 37 | 38 | public EmailNotificationProcessor(INotificationSender notificationSender) 39 | { 40 | this.notificationSender = notificationSender; 41 | } 42 | public void ProcessNotification(string message) 43 | { 44 | notificationSender.SendNotification($"{message}"); 45 | } 46 | } 47 | 48 | public class EmailNotificationSender : INotificationSender 49 | { 50 | public void SendNotification(string message) 51 | { 52 | Console.WriteLine($"Email: {message}"); 53 | } 54 | } -------------------------------------------------------------------------------- /BridgePattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using BridgePattern.Demo; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | // Add services to the container. 7 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 8 | builder.Services.AddEndpointsApiExplorer(); 9 | builder.Services.AddSwaggerGen(); 10 | 11 | builder.Services.AddSingleton(); 12 | builder.Services.AddSingleton(); 13 | 14 | var app = builder.Build(); 15 | 16 | // Configure the HTTP request pipeline. 17 | if (app.Environment.IsDevelopment()) 18 | { 19 | app.UseSwagger(); 20 | app.UseSwaggerUI(); 21 | } 22 | 23 | app.UseHttpsRedirection(); 24 | 25 | app.MapPost("/notification", (INotificationProcessor notificationProcessor, [FromBody] string message) => 26 | { 27 | notificationProcessor.ProcessNotification(message); 28 | return Results.Ok(); 29 | }) 30 | .WithName("Notification"); 31 | 32 | app.Run(); -------------------------------------------------------------------------------- /BridgePattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:12126", 8 | "sslPort": 44317 9 | } 10 | }, 11 | "profiles": { 12 | "BridgePattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7051;http://localhost:5051", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /BridgePattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /BridgePattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /BuilderPattern.Demo/BuilderPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /BuilderPattern.Demo/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace BuilderPattern.Demo.Controllers 4 | { 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class WeatherForecastController : ControllerBase 8 | { 9 | private static readonly string[] Summaries = new[] 10 | { 11 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 12 | }; 13 | 14 | private readonly ILogger _logger; 15 | private readonly IUser user; 16 | 17 | public WeatherForecastController(ILogger logger, IUser user) 18 | { 19 | _logger = logger; 20 | this.user = user; 21 | } 22 | 23 | [HttpGet(Name = "GetWeatherForecast")] 24 | public IUser Get() 25 | { 26 | return user; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /BuilderPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using BuilderPattern.Demo; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | 7 | builder.Services.AddControllers(); 8 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 9 | builder.Services.AddEndpointsApiExplorer(); 10 | builder.Services.AddSwaggerGen(); 11 | 12 | builder.Services.AddSingleton(new User.UserBuilder() 13 | .WithName("John") 14 | .WithAddress("123 Street") 15 | .Build()); 16 | 17 | var app = builder.Build(); 18 | 19 | // Configure the HTTP request pipeline. 20 | if (app.Environment.IsDevelopment()) 21 | { 22 | app.UseSwagger(); 23 | app.UseSwaggerUI(); 24 | } 25 | 26 | app.UseHttpsRedirection(); 27 | 28 | app.UseAuthorization(); 29 | 30 | app.MapControllers(); 31 | 32 | app.Run(); 33 | -------------------------------------------------------------------------------- /BuilderPattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:26010", 8 | "sslPort": 44338 9 | } 10 | }, 11 | "profiles": { 12 | "BuilderPattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7116;http://localhost:5116", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /BuilderPattern.Demo/User.cs: -------------------------------------------------------------------------------- 1 | namespace BuilderPattern.Demo; 2 | 3 | public interface IUser 4 | { 5 | string Name { get; } 6 | string Address { get; } 7 | int Age { get; } 8 | } 9 | 10 | public class User : IUser 11 | { 12 | private string name; 13 | private int age; 14 | private string address; 15 | 16 | private User() { } 17 | 18 | public string Name => name; 19 | 20 | public string Address => address; 21 | 22 | public int Age => age; 23 | 24 | public class UserBuilder 25 | { 26 | private readonly User user; 27 | 28 | public UserBuilder() 29 | { 30 | user = new User(); 31 | } 32 | 33 | public UserBuilder WithName(string name) 34 | { 35 | user.name = name; 36 | return this; 37 | } 38 | 39 | public UserBuilder WithAge(int age) 40 | { 41 | user.age = age; 42 | return this; 43 | } 44 | 45 | public UserBuilder WithAddress(string address) 46 | { 47 | user.address = address; 48 | return this; 49 | } 50 | 51 | public User Build() => user; 52 | } 53 | } -------------------------------------------------------------------------------- /BuilderPattern.Demo/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace BuilderPattern.Demo 2 | { 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /BuilderPattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /BuilderPattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /ChainOfResponsibility.Demo/ChainOfResponsibility.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /ChainOfResponsibility.Demo/Program.cs: -------------------------------------------------------------------------------- 1 |  2 | using ChainOfResponsibility.Demo; 3 | 4 | var manager = new SeniorManager(); 5 | var vp = new VicePresident(); 6 | var coo = new COO(); 7 | 8 | manager.SetSupervisor(vp); 9 | vp.SetSupervisor(coo); 10 | 11 | var expense = new ExpenseReport("Monitor", 100); 12 | Console.WriteLine(expense); 13 | manager.ApproveRequest(expense); 14 | Console.WriteLine("------------------------------"); 15 | 16 | 17 | expense = new ExpenseReport("Desk", 900); 18 | Console.WriteLine(expense); 19 | manager.ApproveRequest(expense); 20 | Console.WriteLine("------------------------------"); 21 | 22 | expense = new ExpenseReport("Travel", 5500); 23 | Console.WriteLine(expense); 24 | manager.ApproveRequest(expense); 25 | Console.WriteLine("------------------------------"); 26 | -------------------------------------------------------------------------------- /ChainOfResponsibility.Demo/SeniorManager.cs: -------------------------------------------------------------------------------- 1 | namespace ChainOfResponsibility.Demo; 2 | 3 | internal record ExpenseReport(string Name, int Amount); 4 | 5 | internal interface IManager 6 | { 7 | void SetSupervisor(IManager manager); 8 | void ApproveRequest(ExpenseReport expenseReport); 9 | } 10 | 11 | internal class SeniorManager : IManager 12 | { 13 | private IManager manager; 14 | public void ApproveRequest(ExpenseReport expenseReport) 15 | { 16 | if(expenseReport.Amount < 500) Console.WriteLine("Approved by Manager"); 17 | else manager?.ApproveRequest(expenseReport); 18 | } 19 | 20 | public void SetSupervisor(IManager manager) 21 | { 22 | this.manager = manager; 23 | } 24 | } 25 | 26 | internal class VicePresident : IManager 27 | { 28 | private IManager manager; 29 | public void ApproveRequest(ExpenseReport expenseReport) 30 | { 31 | if (expenseReport.Amount < 1000) Console.WriteLine("Approved by VP"); 32 | else manager?.ApproveRequest(expenseReport); 33 | } 34 | 35 | public void SetSupervisor(IManager manager) 36 | { 37 | this.manager = manager; 38 | } 39 | } 40 | 41 | internal class COO : IManager 42 | { 43 | private IManager manager; 44 | public void ApproveRequest(ExpenseReport expenseReport) 45 | { 46 | if (expenseReport.Amount < 5000) Console.WriteLine("Approved by COO"); 47 | else Console.WriteLine("No approved"); 48 | } 49 | 50 | public void SetSupervisor(IManager manager) 51 | { 52 | this.manager=manager; 53 | } 54 | } -------------------------------------------------------------------------------- /CommandPattern.Demo/Command.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern.Demo; 2 | 3 | public interface IMessage { } 4 | 5 | public interface ICommand 6 | { 7 | bool Execute(IMessage message); 8 | bool Rollback(IMessage message); 9 | } 10 | 11 | public class OrderCommand : ICommand 12 | { 13 | private readonly IProxy orderProxy; 14 | 15 | public OrderCommand(IProxy orderProxy) 16 | { 17 | this.orderProxy = orderProxy; 18 | } 19 | 20 | public bool Execute(IMessage message) 21 | { 22 | return orderProxy.Create((Order)message); 23 | } 24 | 25 | public bool Rollback(IMessage message) 26 | { 27 | return orderProxy.Delete((Order)message); 28 | } 29 | } 30 | 31 | public class InventoryCommand : ICommand 32 | { 33 | private readonly IProxy inventoryProxy; 34 | 35 | public InventoryCommand(IProxy inventoryProxy) 36 | { 37 | this.inventoryProxy = inventoryProxy; 38 | } 39 | 40 | public bool Execute(IMessage message) 41 | { 42 | return inventoryProxy.Create((Inventory)message); 43 | } 44 | 45 | public bool Rollback(IMessage message) 46 | { 47 | return inventoryProxy.Delete((Inventory)message); 48 | } 49 | } -------------------------------------------------------------------------------- /CommandPattern.Demo/CommandPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /CommandPattern.Demo/IOrchestrator.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern.Demo 2 | { 3 | public interface IOrchestrator 4 | { 5 | bool CreateOrder(Order order); 6 | } 7 | } -------------------------------------------------------------------------------- /CommandPattern.Demo/Orchestrator.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern.Demo; 2 | 3 | public class Orchestrator : IOrchestrator 4 | { 5 | private readonly ICommand orderCommand; 6 | private readonly ICommand inventoryCommand; 7 | 8 | public Orchestrator(ICommand orderCommand, ICommand inventoryCommand) 9 | { 10 | this.orderCommand = orderCommand; 11 | this.inventoryCommand = inventoryCommand; 12 | } 13 | 14 | public bool CreateOrder(Order order) 15 | { 16 | if (orderCommand.Execute(order)) 17 | { 18 | if (inventoryCommand.Execute(new Inventory(order.ProductName, order.Quantity))) 19 | { 20 | return true; 21 | } 22 | else 23 | { 24 | return orderCommand.Rollback(order); 25 | } 26 | } 27 | return false; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CommandPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using CommandPattern.Demo; 2 | using Microsoft.AspNetCore.Mvc; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | // Add services to the container. 7 | builder.Services.AddControllers(); 8 | builder.Services.AddEndpointsApiExplorer(); 9 | builder.Services.AddSwaggerGen(); 10 | 11 | builder.Services.AddSingleton, OrderProxy>(); 12 | builder.Services.AddSingleton, InventoryProxy>(); 13 | builder.Services.AddSingleton(x => new Orchestrator( 14 | new OrderCommand(x.GetService>()), 15 | new InventoryCommand(x.GetService>()) 16 | )); 17 | 18 | var app = builder.Build(); 19 | 20 | // Configure the HTTP request pipeline. 21 | if (app.Environment.IsDevelopment()) 22 | { 23 | app.UseSwagger(); 24 | app.UseSwaggerUI(); 25 | } 26 | 27 | app.UseHttpsRedirection(); 28 | 29 | app.UseAuthorization(); 30 | 31 | app.MapControllers(); 32 | 33 | app.MapPost("/api/order", ([FromBody] Order order, [FromServices] IOrchestrator orchestrator) => 34 | { 35 | return orchestrator.CreateOrder(order); 36 | }); 37 | 38 | app.Run(); -------------------------------------------------------------------------------- /CommandPattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:26199", 8 | "sslPort": 44338 9 | } 10 | }, 11 | "profiles": { 12 | "CommandPattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7117;http://localhost:5117", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CommandPattern.Demo/Proxy.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern.Demo; 2 | public interface IProxy 3 | { 4 | bool Create(T item); 5 | bool Delete(T item); 6 | } 7 | 8 | public class InventoryProxy : IProxy 9 | { 10 | public bool Create(Inventory inventory) 11 | { 12 | Console.WriteLine($"Created inventory for product: {inventory.ProductName}"); 13 | return false; 14 | } 15 | 16 | public bool Delete(Inventory inventory) 17 | { 18 | Console.WriteLine($"Deleted inventory for product: {inventory.ProductName}"); 19 | return true; 20 | } 21 | } 22 | 23 | public record Inventory(string ProductName, int Quentity) : IMessage; 24 | 25 | public class OrderProxy : IProxy 26 | { 27 | public bool Create(Order order) 28 | { 29 | Console.WriteLine($"Created order for product: {order.ProductName}"); 30 | return true; 31 | } 32 | 33 | public bool Delete(Order order) 34 | { 35 | Console.WriteLine($"Deleted order for product: {order.ProductName}"); 36 | return true; 37 | } 38 | } 39 | 40 | public record Order(string ProductName, int Quantity) : IMessage; 41 | -------------------------------------------------------------------------------- /CommandPattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /CommandPattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /CompositePattern.Demo/CompositeNode.cs: -------------------------------------------------------------------------------- 1 | namespace CompositePattern.Demo; 2 | internal class CompositeNode : Node 3 | { 4 | private List children = new(); 5 | private readonly string name; 6 | private readonly Node? parentNode; 7 | 8 | public override string Name => name; 9 | 10 | public CompositeNode(string name, Node? parentNode = null) 11 | { 12 | this.name = name; 13 | this.parentNode = parentNode; 14 | } 15 | 16 | public override void Add(Node node) 17 | { 18 | children.Add(node); 19 | } 20 | 21 | public override void Remove(Node node) 22 | { 23 | children.Remove(node); 24 | } 25 | 26 | public override void PrintParent() 27 | { 28 | if (parentNode != null) 29 | Console.WriteLine($"Parent: {parentNode.Name}"); 30 | else 31 | Console.WriteLine("Root node"); 32 | } 33 | 34 | public override void PrintChildren() 35 | { 36 | Console.WriteLine 37 | ($"Children: {string.Join(',', children.Select(c => c.Name))}"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /CompositePattern.Demo/CompositePattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /CompositePattern.Demo/LeafNode.cs: -------------------------------------------------------------------------------- 1 | namespace CompositePattern.Demo; 2 | internal class LeafNode : Node 3 | { 4 | private readonly string name; 5 | private readonly Node parentNode; 6 | 7 | public override string Name => name; 8 | 9 | public LeafNode(string name, Node parentNode) 10 | { 11 | this.name = name; 12 | this.parentNode = parentNode; 13 | } 14 | 15 | public override void PrintParent() 16 | { 17 | Console.WriteLine($"Parent: {parentNode.Name}"); 18 | } 19 | } -------------------------------------------------------------------------------- /CompositePattern.Demo/Node.cs: -------------------------------------------------------------------------------- 1 | namespace CompositePattern.Demo; 2 | internal abstract class Node 3 | { 4 | public abstract string Name { get; } 5 | 6 | public virtual void Add(Node node) => 7 | throw new NotImplementedException(); 8 | 9 | public virtual void Remove(Node node) => 10 | throw new NotImplementedException(); 11 | 12 | public virtual void PrintChildren() => 13 | throw new NotImplementedException(); 14 | 15 | public virtual void PrintParent() => 16 | throw new NotImplementedException(); 17 | } -------------------------------------------------------------------------------- /CompositePattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using CompositePattern.Demo; 2 | 3 | var root = new CompositeNode("Root"); 4 | 5 | var node1 = new CompositeNode("node1", root); 6 | var leaf11 = new LeafNode("leaf11", node1); 7 | var leaf12 = new LeafNode("leaf12", node1); 8 | node1.Add(leaf11); 9 | node1.Add(leaf12); 10 | 11 | var node2 = new CompositeNode("node2", root); 12 | var leaf1 = new LeafNode("leaf1", root); 13 | 14 | root.Add(leaf1); 15 | root.Add(node1); 16 | root.Add(node2); 17 | 18 | Console.WriteLine("Root ======"); 19 | root.PrintParent(); 20 | root.PrintChildren(); 21 | 22 | Console.WriteLine("leaf1 ======"); 23 | leaf1.PrintParent(); 24 | 25 | Console.WriteLine("node1 ======"); 26 | node1.PrintParent(); 27 | node1.PrintChildren(); 28 | 29 | Console.WriteLine("leaf11 ======"); 30 | leaf11.PrintParent(); 31 | leaf11.PrintChildren(); -------------------------------------------------------------------------------- /DecoratorPattern.Demo/CakeMessageDecorator.cs: -------------------------------------------------------------------------------- 1 | namespace DecoratorPattern.Demo; 2 | public class CakeMessageDecorator 3 | : ICakeMessageDecorator 4 | { 5 | private readonly ICake cake; 6 | 7 | public CakeMessageDecorator(ICake cake) 8 | { 9 | this.cake = cake; 10 | } 11 | 12 | public void Decorate(string message) 13 | { 14 | cake.AddLayer($"Message for the cake: {message}"); 15 | } 16 | } -------------------------------------------------------------------------------- /DecoratorPattern.Demo/ChocolateCake.cs: -------------------------------------------------------------------------------- 1 | namespace DecoratorPattern.Demo; 2 | public class ChocolateCake : ICake 3 | { 4 | private readonly List layers = new(); 5 | public void AddLayer(string layer) 6 | { 7 | layers.Add(layer); 8 | } 9 | 10 | public void PrintLayers() 11 | { 12 | foreach (var layer in layers) 13 | { 14 | Console.WriteLine($"Chocolate Layer: {layer}"); 15 | Console.WriteLine(" ---------- "); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /DecoratorPattern.Demo/DecoratorPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /DecoratorPattern.Demo/ICake.cs: -------------------------------------------------------------------------------- 1 | namespace DecoratorPattern.Demo; 2 | public interface ICake 3 | { 4 | void AddLayer(string layer); 5 | void PrintLayers(); 6 | } -------------------------------------------------------------------------------- /DecoratorPattern.Demo/ICakeMessageDecorator.cs: -------------------------------------------------------------------------------- 1 | namespace DecoratorPattern.Demo; 2 | public interface ICakeMessageDecorator 3 | { 4 | void Decorate(string message); 5 | } -------------------------------------------------------------------------------- /DecoratorPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using DecoratorPattern.Demo; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 7 | builder.Services.AddEndpointsApiExplorer(); 8 | builder.Services.AddSwaggerGen(); 9 | 10 | builder.Services.AddSingleton(); 11 | builder.Services.AddSingleton(); 12 | 13 | var app = builder.Build(); 14 | 15 | // Configure the HTTP request pipeline. 16 | if (app.Environment.IsDevelopment()) 17 | { 18 | app.UseSwagger(); 19 | app.UseSwaggerUI(); 20 | } 21 | 22 | app.UseHttpsRedirection(); 23 | 24 | app.MapGet("/decorate", ( 25 | ICakeMessageDecorator cakeMessageDecorator, 26 | ICake cake) => 27 | { 28 | cakeMessageDecorator.Decorate("Happy Birthday!"); 29 | cake.PrintLayers(); 30 | }) 31 | .WithName("Decorate"); 32 | 33 | app.Run(); -------------------------------------------------------------------------------- /DecoratorPattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:21857", 8 | "sslPort": 44331 9 | } 10 | }, 11 | "profiles": { 12 | "DecoratorPattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7289;http://localhost:5289", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /DecoratorPattern.Demo/VanillaCake.cs: -------------------------------------------------------------------------------- 1 | namespace DecoratorPattern.Demo; 2 | public class VanillaCake : ICake 3 | { 4 | private readonly List layers = new(); 5 | public void AddLayer(string layer) 6 | { 7 | layers.Add(layer); 8 | } 9 | 10 | public void PrintLayers() 11 | { 12 | foreach (var layer in layers) 13 | { 14 | Console.WriteLine($"Layer: {layer}"); 15 | Console.WriteLine(" ---------- "); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /DecoratorPattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /DecoratorPattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32014.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FacadePattern.Demo", "FacadePattern.Demo\FacadePattern.Demo.csproj", "{FAF730D3-F4DB-4F56-B349-CB1197DB23D7}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {FAF730D3-F4DB-4F56-B349-CB1197DB23D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {FAF730D3-F4DB-4F56-B349-CB1197DB23D7}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {FAF730D3-F4DB-4F56-B349-CB1197DB23D7}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {FAF730D3-F4DB-4F56-B349-CB1197DB23D7}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {C47D8C02-5F6A-4FC7-BC6F-D27106BDAA50} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/Business.cs: -------------------------------------------------------------------------------- 1 | namespace FacadePattern.Demo; 2 | 3 | public interface IInventoryService 4 | { 5 | Task GetAsync(); 6 | } 7 | 8 | internal class InventoryService : IInventoryService 9 | { 10 | public Task GetAsync() 11 | { 12 | return Task.FromResult(new string[] { "Book", "Pen" }); 13 | } 14 | } 15 | 16 | public interface IPaymentService 17 | { 18 | Task PayAsync(double amount, string item); 19 | } 20 | 21 | internal class PaymentService : IPaymentService 22 | { 23 | public Task PayAsync(double amount, string item) 24 | { 25 | Console.WriteLine($"Paying amount: {amount} for item: {item}"); 26 | return Task.CompletedTask; 27 | } 28 | } 29 | 30 | public interface INotificationService 31 | { 32 | Task SendAsync(string message); 33 | } 34 | 35 | internal class NotificationService : INotificationService 36 | { 37 | public Task SendAsync(string message) 38 | { 39 | Console.WriteLine($"Sending notification message: {message}"); 40 | return Task.CompletedTask; 41 | } 42 | } -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/Controllers/InventoryController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace FacadePattern.Demo.Controllers; 4 | 5 | [Route("api/[controller]")] 6 | [ApiController] 7 | public class InventoryController : ControllerBase 8 | { 9 | // GET: api/ 10 | [HttpGet] 11 | public IEnumerable Get() 12 | { 13 | return new string[] { "value1", "value2" }; 14 | } 15 | } -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/Controllers/NotificationController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace FacadePattern.Demo.Controllers; 4 | 5 | [Route("api/[controller]")] 6 | [ApiController] 7 | public class NotificationController : ControllerBase 8 | { 9 | private readonly INotificationService notificationService; 10 | 11 | public NotificationController(INotificationService notificationService) 12 | { 13 | this.notificationService = notificationService; 14 | } 15 | 16 | // POST api/ 17 | [HttpPost] 18 | public async Task Post([FromBody] string message) 19 | { 20 | await notificationService.SendAsync(message); 21 | } 22 | } -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/Controllers/PaymentController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace FacadePattern.Demo.Controllers; 4 | 5 | [Route("api/[controller]")] 6 | [ApiController] 7 | public class PaymentController : ControllerBase 8 | { 9 | private readonly IPaymentService paymentService; 10 | 11 | public PaymentController(IPaymentService paymentService) 12 | { 13 | this.paymentService = paymentService; 14 | } 15 | 16 | // POST api/ 17 | [HttpPost] 18 | public async Task Post([FromBody] string item, [FromBody] double amount) 19 | { 20 | await paymentService.PayAsync(amount, item); 21 | } 22 | } -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/Controllers/PurchaseFacadeController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace FacadePattern.Demo.Controllers; 4 | 5 | [Route("api/[controller]")] 6 | [ApiController] 7 | public class PurchaseFacadeController : ControllerBase 8 | { 9 | private readonly IInventoryService inventoryService; 10 | private readonly IPaymentService paymentService; 11 | private readonly INotificationService notificationService; 12 | 13 | public PurchaseFacadeController(IInventoryService inventoryService, 14 | IPaymentService paymentService, 15 | INotificationService notificationService) 16 | { 17 | this.inventoryService = inventoryService; 18 | this.paymentService = paymentService; 19 | this.notificationService = notificationService; 20 | } 21 | 22 | // POST api/ 23 | [HttpPost] 24 | public async Task Post([FromBody] string item, [FromBody] double amount) 25 | { 26 | var inventories = await inventoryService.GetAsync(); 27 | if (inventories.Any(i => i == item)) return BadRequest(); 28 | 29 | await paymentService.PayAsync(amount, item); 30 | 31 | await notificationService.SendAsync($"Item: {item} purchased with amount: {amount}"); 32 | 33 | return Ok(); 34 | } 35 | } -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | // Add services to the container. 4 | 5 | builder.Services.AddControllers(); 6 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 7 | builder.Services.AddEndpointsApiExplorer(); 8 | builder.Services.AddSwaggerGen(); 9 | 10 | var app = builder.Build(); 11 | 12 | // Configure the HTTP request pipeline. 13 | if (app.Environment.IsDevelopment()) 14 | { 15 | app.UseSwagger(); 16 | app.UseSwaggerUI(); 17 | } 18 | 19 | app.UseHttpsRedirection(); 20 | 21 | app.UseAuthorization(); 22 | 23 | app.MapControllers(); 24 | 25 | app.Run(); 26 | -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:29913", 8 | "sslPort": 44344 9 | } 10 | }, 11 | "profiles": { 12 | "FacadePattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7134;http://localhost:5134", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /FacadePattern.Demo/FacadePattern.Demo/FacadePattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/Controllers/LawnmowerCatalogController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 4 | 5 | namespace FactoryMethodPattern.Demo.Controllers 6 | { 7 | [Route("api/[controller]")] 8 | [ApiController] 9 | public class LawnmowerCatalogController : ControllerBase 10 | { 11 | private readonly Func lawnmowerCatalogAbstractFactory; 12 | 13 | public LawnmowerCatalogController(Func lawnmowerCatalogAbstractFactory) 14 | { 15 | this.lawnmowerCatalogAbstractFactory = lawnmowerCatalogAbstractFactory; 16 | } 17 | 18 | // GET api//5 19 | [HttpGet] 20 | public IEnumerable Get(string manufacturer, string type) 21 | { 22 | return lawnmowerCatalogAbstractFactory(manufacturer).CreateCatalog(type).GetLawnmowers(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace FactoryMethodPattern.Demo.Controllers 4 | { 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class WeatherForecastController : ControllerBase 8 | { 9 | private static readonly string[] Summaries = new[] 10 | { 11 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 12 | }; 13 | 14 | private readonly ILogger _logger; 15 | 16 | public WeatherForecastController(ILogger logger) 17 | { 18 | _logger = logger; 19 | } 20 | 21 | [HttpGet(Name = "GetWeatherForecast")] 22 | public IEnumerable Get() 23 | { 24 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 25 | { 26 | Date = DateTime.Now.AddDays(index), 27 | TemperatureC = Random.Shared.Next(-20, 55), 28 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 29 | }) 30 | .ToArray(); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/FactoryMethodPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/ILawnmowerCatalog.cs: -------------------------------------------------------------------------------- 1 | namespace FactoryMethodPattern.Demo 2 | { 3 | public interface ILawnmowerCatalog 4 | { 5 | Lawnmower[] GetLawnmowers(); 6 | } 7 | 8 | public class DieselLawnmowerCatalog : ILawnmowerCatalog 9 | { 10 | public Lawnmower[] GetLawnmowers() 11 | { 12 | return new[] { new Lawnmower { Name = "I am Diesel Lawnmower" } }; 13 | } 14 | } 15 | 16 | public class XyzDieselLawnmowerCatalog : ILawnmowerCatalog 17 | { 18 | public Lawnmower[] GetLawnmowers() 19 | { 20 | return new[] { new Lawnmower { Name = "XYZ: I am Diesel Lawnmower" } }; 21 | } 22 | } 23 | 24 | public class ElectricLawnmowerCatalog : ILawnmowerCatalog 25 | { 26 | public Lawnmower[] GetLawnmowers() 27 | { 28 | return new[] { new Lawnmower { Name = "I am Electric Lawnmower" } }; 29 | } 30 | } 31 | 32 | public class XyzElectricLawnmowerCatalog : ILawnmowerCatalog 33 | { 34 | public Lawnmower[] GetLawnmowers() 35 | { 36 | return new[] { new Lawnmower { Name = "XYZ: I am Electric Lawnmower" } }; 37 | } 38 | } 39 | 40 | public class ManualLawnmowerCatalog : ILawnmowerCatalog 41 | { 42 | public Lawnmower[] GetLawnmowers() 43 | { 44 | return new[] { new Lawnmower { Name = "I am Manual Lawnmower" } }; 45 | } 46 | } 47 | 48 | public class XyzManualLawnmowerCatalog : ILawnmowerCatalog 49 | { 50 | public Lawnmower[] GetLawnmowers() 51 | { 52 | return new[] { new Lawnmower { Name = "XYZ: I am Manual Lawnmower" } }; 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/ILawnmowerCatalogAbstractFactory.cs: -------------------------------------------------------------------------------- 1 | namespace FactoryMethodPattern.Demo 2 | { 3 | public interface ILawnmowerCatalogAbstractFactory 4 | { 5 | ILawnmowerCatalogFactory CreateFactory(string manufacturer); 6 | } 7 | 8 | public class LawnmowerCatalogAbstractFactory : ILawnmowerCatalogAbstractFactory 9 | { 10 | public ILawnmowerCatalogFactory CreateFactory(string manufacturer) 11 | { 12 | return manufacturer switch 13 | { 14 | "Xyz" => new XyzLawnmowerCatalogFactory(), 15 | _ => new LawnmowerCatalogFactory() 16 | }; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/ILawnmowerCatalogFactory.cs: -------------------------------------------------------------------------------- 1 | namespace FactoryMethodPattern.Demo 2 | { 3 | public interface ILawnmowerCatalogFactory 4 | { 5 | ILawnmowerCatalog CreateCatalog(string type); 6 | } 7 | } -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/Lawnmower.cs: -------------------------------------------------------------------------------- 1 | namespace FactoryMethodPattern.Demo 2 | { 3 | public class Lawnmower 4 | { 5 | public string Name { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/LawnmowerCatalogFactory.cs: -------------------------------------------------------------------------------- 1 | namespace FactoryMethodPattern.Demo 2 | { 3 | public class LawnmowerCatalogFactory : ILawnmowerCatalogFactory 4 | { 5 | public ILawnmowerCatalog CreateCatalog(string type) 6 | { 7 | return type switch 8 | { 9 | "Diesel" => new DieselLawnmowerCatalog(), 10 | "Electric" => new ElectricLawnmowerCatalog(), 11 | _ => new ManualLawnmowerCatalog(), 12 | }; 13 | } 14 | } 15 | 16 | public class XyzLawnmowerCatalogFactory : ILawnmowerCatalogFactory 17 | { 18 | public ILawnmowerCatalog CreateCatalog(string type) 19 | { 20 | return type switch 21 | { 22 | "Diesel" => new XyzDieselLawnmowerCatalog(), 23 | "Electric" => new XyzElectricLawnmowerCatalog(), 24 | _ => new XyzManualLawnmowerCatalog(), 25 | }; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using FactoryMethodPattern.Demo; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | 7 | builder.Services.AddControllers(); 8 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 9 | builder.Services.AddEndpointsApiExplorer(); 10 | builder.Services.AddSwaggerGen(); 11 | 12 | 13 | builder.Services.AddSingleton>(manufacturer => { 14 | return manufacturer switch 15 | { 16 | "Xyz" => new XyzLawnmowerCatalogFactory(), 17 | _ => new LawnmowerCatalogFactory() 18 | }; 19 | }); 20 | 21 | var app = builder.Build(); 22 | 23 | // Configure the HTTP request pipeline. 24 | if (app.Environment.IsDevelopment()) 25 | { 26 | app.UseSwagger(); 27 | app.UseSwaggerUI(); 28 | } 29 | 30 | app.UseHttpsRedirection(); 31 | 32 | app.UseAuthorization(); 33 | 34 | app.MapControllers(); 35 | 36 | app.Run(); 37 | -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:26980", 8 | "sslPort": 44339 9 | } 10 | }, 11 | "profiles": { 12 | "FactoryMethodPattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7120;http://localhost:5120", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace FactoryMethodPattern.Demo 2 | { 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /FactoryMethodPattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32014.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlyweightPattern.Demo", "FlyweightPattern.Demo\FlyweightPattern.Demo.csproj", "{2899972F-0C64-49E2-A63B-8D22FD22E423}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {2899972F-0C64-49E2-A63B-8D22FD22E423}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {2899972F-0C64-49E2-A63B-8D22FD22E423}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {2899972F-0C64-49E2-A63B-8D22FD22E423}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {2899972F-0C64-49E2-A63B-8D22FD22E423}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {5F90A316-EE4E-4272-9993-899C8C7EE885} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/AudiCar.cs: -------------------------------------------------------------------------------- 1 | namespace FlyweightPattern.Demo; 2 | 3 | public class AudiCar : ICar 4 | { 5 | public string Color { get; private set; } 6 | 7 | public string Engine { get; private set; } 8 | 9 | public AudiCar(string color, string engine) 10 | { 11 | Color = color; 12 | Engine = engine; 13 | } 14 | 15 | public void SetLocation(decimal lat, decimal lon) 16 | { 17 | Console.WriteLine($"Current location of Audi Car with color: {Color}, Engine: {Engine} is {lat}, {lon}"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/BmwCar.cs: -------------------------------------------------------------------------------- 1 | namespace FlyweightPattern.Demo; 2 | public class BmwCar : ICar 3 | { 4 | public string Color {get; private set;} 5 | 6 | public string Engine {get; private set;} 7 | 8 | public BmwCar(string color, string engine) 9 | { 10 | Color = color; 11 | Engine = engine; 12 | } 13 | 14 | public void SetLocation(decimal lat, decimal lon) 15 | { 16 | Console.WriteLine($"Current location of BMW Car with color: {Color}, Engine: {Engine} is {lat}, {lon}"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/CarFactroy.cs: -------------------------------------------------------------------------------- 1 | namespace FlyweightPattern.Demo; 2 | 3 | public interface ICarFactroy 4 | { 5 | ICar GetCar(string type); 6 | } 7 | 8 | public class CarFactroy : ICarFactroy 9 | { 10 | private readonly IDictionary cars = new Dictionary(); 11 | 12 | public ICar GetCar(string type) 13 | { 14 | if (cars.ContainsKey(type)) return cars[type]; 15 | var car = CreateCar(type); 16 | cars.Add(type, car); 17 | return car; 18 | } 19 | 20 | private ICar CreateCar(string type) => 21 | type switch 22 | { 23 | "Bmw" => new BmwCar("V8", "Red"), 24 | "Audi" => new AudiCar("V6", "Blue"), 25 | _ => throw new ArgumentException("Invalid Choice") 26 | }; 27 | } -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/CarManager.cs: -------------------------------------------------------------------------------- 1 | namespace FlyweightPattern.Demo; 2 | 3 | public interface ICarManager 4 | { 5 | void SetLocation(decimal lat, decimal lon); 6 | } 7 | 8 | public class CarManager : ICarManager 9 | { 10 | private readonly ICar car; 11 | 12 | public CarManager(ICarFactroy carFactroy, string type) 13 | { 14 | car = carFactroy.GetCar(type); 15 | } 16 | 17 | public void SetLocation(decimal lat, decimal lon) 18 | { 19 | car.SetLocation(lat, lon); 20 | } 21 | } -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace FlyweightPattern.Demo.Controllers 4 | { 5 | [ApiController] 6 | [Route("[controller]")] 7 | public class WeatherForecastController : ControllerBase 8 | { 9 | private static readonly string[] Summaries = new[] 10 | { 11 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 12 | }; 13 | 14 | private readonly ILogger _logger; 15 | 16 | public WeatherForecastController(ILogger logger) 17 | { 18 | _logger = logger; 19 | } 20 | 21 | [HttpGet(Name = "GetWeatherForecast")] 22 | public IEnumerable Get() 23 | { 24 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 25 | { 26 | Date = DateTime.Now.AddDays(index), 27 | TemperatureC = Random.Shared.Next(-20, 55), 28 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 29 | }) 30 | .ToArray(); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/ICar.cs: -------------------------------------------------------------------------------- 1 | namespace FlyweightPattern.Demo; 2 | 3 | public interface ICar 4 | { 5 | string Color { get; } 6 | string Engine { get; } 7 | 8 | void SetLocation(decimal lat, decimal lon); 9 | } -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = WebApplication.CreateBuilder(args); 2 | 3 | // Add services to the container. 4 | 5 | builder.Services.AddControllers(); 6 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 7 | builder.Services.AddEndpointsApiExplorer(); 8 | builder.Services.AddSwaggerGen(); 9 | 10 | var app = builder.Build(); 11 | 12 | // Configure the HTTP request pipeline. 13 | if (app.Environment.IsDevelopment()) 14 | { 15 | app.UseSwagger(); 16 | app.UseSwaggerUI(); 17 | } 18 | 19 | app.UseHttpsRedirection(); 20 | 21 | app.UseAuthorization(); 22 | 23 | app.MapControllers(); 24 | 25 | app.Run(); 26 | -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:12950", 8 | "sslPort": 44318 9 | } 10 | }, 11 | "profiles": { 12 | "FlyweightPattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7055;http://localhost:5055", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /FlyweightPattern.Demo/FlyweightPattern.Demo/FlyweightPattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /InterpreterPattern.Demo/Context.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace InterpreterPattern.Demo 8 | { 9 | internal class Context 10 | { 11 | public Context(string expression, string value) 12 | { 13 | Expression = expression; 14 | Value = value; 15 | } 16 | 17 | public string Expression { get; } 18 | public string Value { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /InterpreterPattern.Demo/Expression.cs: -------------------------------------------------------------------------------- 1 | namespace InterpreterPattern.Demo; 2 | internal interface IExpression 3 | { 4 | void Evaluate(Context context); 5 | } 6 | 7 | internal class LowerCaseExpression : IExpression 8 | { 9 | public void Evaluate(Context context) 10 | { 11 | context.Value = context.Value.ToLower(); 12 | } 13 | } 14 | 15 | internal class UpperCaseExpression : IExpression 16 | { 17 | public void Evaluate(Context context) 18 | { 19 | context.Value = context.Value.ToUpper(); 20 | } 21 | } -------------------------------------------------------------------------------- /InterpreterPattern.Demo/Interpreter.cs: -------------------------------------------------------------------------------- 1 | namespace InterpreterPattern.Demo; 2 | internal class Interpreter 3 | { 4 | public void Interpret(Context context) 5 | { 6 | var expressions = context.Expression.Split(' '); 7 | var expressionTypes = new List(); 8 | 9 | foreach (var expression in expressions) 10 | { 11 | if(expression == "-l") 12 | expressionTypes.Add(new LowerCaseExpression()); 13 | else if(expression == "-u") 14 | expressionTypes.Add(new UpperCaseExpression()); 15 | } 16 | 17 | foreach (var item in expressionTypes) 18 | { 19 | item.Evaluate(context); 20 | } 21 | 22 | Console.WriteLine(context.Value); 23 | } 24 | } -------------------------------------------------------------------------------- /InterpreterPattern.Demo/InterpreterPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /InterpreterPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 |  2 | using InterpreterPattern.Demo; 3 | 4 | Console.WriteLine("Provide a word with expression"); 5 | var word = Console.ReadLine(); 6 | 7 | var value = word.Substring(0, word.IndexOf("-")); 8 | var expressions = word.Substring(word.IndexOf("-")); 9 | 10 | var interpreter = new Interpreter(); 11 | interpreter.Interpret(new Context(expressions, value)); -------------------------------------------------------------------------------- /Iterator.Demo/Aggregate.cs: -------------------------------------------------------------------------------- 1 | namespace Iterator.Demo; 2 | 3 | internal interface IAggregate 4 | { 5 | T this[int index] { get; set; } 6 | 7 | int Count { get; } 8 | IIterator Iterator { get; } 9 | } 10 | 11 | internal class Aggregate : IAggregate 12 | { 13 | private IIterator _iterator; 14 | private List _list = new List(); 15 | 16 | public T this[int index] 17 | { 18 | get { return _list[index]; } 19 | set { _list.Add(value); } 20 | } 21 | 22 | public IIterator Iterator 23 | { 24 | get 25 | { 26 | if (this._iterator == null) _iterator = new Iterator(this); 27 | return _iterator; 28 | } 29 | } 30 | 31 | public int Count => _list.Count; 32 | } 33 | -------------------------------------------------------------------------------- /Iterator.Demo/Iterator.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Iterator.Demo/Iterator.cs: -------------------------------------------------------------------------------- 1 | namespace Iterator.Demo; 2 | 3 | internal interface IIterator 4 | { 5 | T Next(); 6 | T Current { get; } 7 | bool IsLeft(); 8 | } 9 | 10 | internal record Person(string Name, int Age); 11 | 12 | internal class Iterator : IIterator 13 | { 14 | private readonly IAggregate _aggregate; 15 | int index = 0; 16 | 17 | public Iterator(IAggregate aggregate) 18 | { 19 | this._aggregate = aggregate; 20 | } 21 | 22 | public T Current => _aggregate[index]; 23 | 24 | public bool IsLeft() => index < _aggregate.Count; 25 | 26 | public T Next() 27 | { 28 | index++; 29 | return IsLeft() ? _aggregate[index] : default; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Iterator.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using Iterator.Demo; 2 | 3 | var persons = new Aggregate(); 4 | persons[0] = new Person("John", 30); 5 | persons[1] = new Person("Jane", 20); 6 | persons[3] = new Person("Michael", 10); 7 | 8 | var iterator = persons.Iterator; 9 | 10 | while (iterator.IsLeft()) 11 | { 12 | Console.WriteLine(iterator.Current); 13 | iterator.Next(); 14 | } -------------------------------------------------------------------------------- /MediatorPattern.Demo/Cab.cs: -------------------------------------------------------------------------------- 1 | namespace MediatorPattern.Demo; 2 | 3 | internal interface ICab 4 | { 5 | string Name { get; } 6 | int CurrentLocation { get; } 7 | bool IsFree { get; } 8 | 9 | void Assign(string name, string address); 10 | } 11 | 12 | internal class Cab : ICab 13 | { 14 | private readonly string _name; 15 | private readonly int _location; 16 | private readonly bool _free; 17 | 18 | public Cab(string name, int location, bool free) 19 | { 20 | _name = name; 21 | _location = location; 22 | _free = free; 23 | } 24 | 25 | public string Name => _name; 26 | 27 | public int CurrentLocation => _location; 28 | 29 | public bool IsFree => _free; 30 | 31 | public void Assign(string name, string address) => 32 | Console.WriteLine($"Cab {Name}, assigned to passenger: {name}, {address}"); 33 | } 34 | -------------------------------------------------------------------------------- /MediatorPattern.Demo/CabCallCenter.cs: -------------------------------------------------------------------------------- 1 | namespace MediatorPattern.Demo; 2 | 3 | internal interface ICabCallCenter 4 | { 5 | void Register(ICab cab); 6 | void BookCab(IPassenger passenger); 7 | } 8 | 9 | internal class CabCallCenter : ICabCallCenter 10 | { 11 | private readonly Dictionary cabs 12 | = new Dictionary(); 13 | public void BookCab(IPassenger passenger) 14 | { 15 | foreach (var cab in cabs.Values.Where(c => c.IsFree)) 16 | { 17 | if(IsWithin5MileRadius(cab.CurrentLocation, passenger.Location)) 18 | { 19 | cab.Assign(passenger.Name, passenger.Address); 20 | passenger.Acknowledge(cab.Name); 21 | } 22 | } 23 | } 24 | 25 | public void Register(ICab cab) 26 | { 27 | if (!cabs.ContainsValue(cab)) cabs.Add(cab.Name, cab); 28 | } 29 | 30 | private bool IsWithin5MileRadius(int cabLocation, int passengerLocation) 31 | => Math.Abs(cabLocation - passengerLocation) < 5; 32 | } -------------------------------------------------------------------------------- /MediatorPattern.Demo/MediatorPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /MediatorPattern.Demo/Passenger.cs: -------------------------------------------------------------------------------- 1 | namespace MediatorPattern.Demo; 2 | 3 | internal interface IPassenger 4 | { 5 | string Name { get; } 6 | string Address { get; } 7 | int Location { get; } 8 | 9 | void Acknowledge(string name); 10 | } 11 | 12 | internal class Passenger : IPassenger 13 | { 14 | private string _name; 15 | private string _address; 16 | private int _location; 17 | 18 | public Passenger(string name, string address, int location) 19 | { 20 | _name = name; 21 | _address = address; 22 | _location = location; 23 | } 24 | public string Name => _name; 25 | 26 | public string Address => _address; 27 | 28 | public int Location => _location; 29 | 30 | public void Acknowledge(string name) => 31 | Console.WriteLine($"Passenger {Name}, Cab: {name}"); 32 | } -------------------------------------------------------------------------------- /MediatorPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using MediatorPattern.Demo; 2 | 3 | var callCenter = new CabCallCenter(); 4 | 5 | var passenger1 = new Passenger("Passender1", "123 Street", 10); 6 | var passenger2 = new Passenger("Passender2", "456 Street", 25); 7 | 8 | var cab1 = new Cab("Cab1", 11, true); 9 | var cab2 = new Cab("Cab2", 22, true); 10 | 11 | callCenter.Register(cab1); 12 | callCenter.Register(cab2); 13 | 14 | callCenter.BookCab(passenger1); 15 | callCenter.BookCab(passenger2); 16 | 17 | Console.ReadLine(); -------------------------------------------------------------------------------- /MementoPattern.Demo/Employee.cs: -------------------------------------------------------------------------------- 1 | namespace MementoPattern.Demo; 2 | 3 | internal record Memento(int Id, string Name, int Age, string Phone); 4 | 5 | internal interface IEmployee 6 | { 7 | int Id { get; } 8 | int Age { get; set; } 9 | string Name { get; set; } 10 | string Phone { get; set; } 11 | 12 | Memento Create(); 13 | void Undo(Memento memento); 14 | } 15 | 16 | internal class Employee : IEmployee 17 | { 18 | public int Id { get; set; } 19 | public string Name { get; set; } 20 | public int Age { get; set; } 21 | public string Phone { get; set; } 22 | 23 | public Memento Create() => new Memento(Id, Name, Age, Phone); 24 | 25 | public void Undo(Memento memento) 26 | { 27 | Id = memento.Id; 28 | Name = memento.Name; 29 | Age = memento.Age; 30 | Phone = memento.Phone; 31 | } 32 | } -------------------------------------------------------------------------------- /MementoPattern.Demo/EmployeeManager.cs: -------------------------------------------------------------------------------- 1 | namespace MementoPattern.Demo; 2 | 3 | internal interface IEmployeeManager 4 | { 5 | void AddMemento(int id,Memento memento); 6 | Memento GetMemento(int id); 7 | } 8 | 9 | internal class EmployeeManager : IEmployeeManager 10 | { 11 | private readonly Dictionary> mementos = new Dictionary>(); 12 | 13 | public void AddMemento(int id, Memento memento) 14 | { 15 | if (!mementos.ContainsKey(id)) mementos.Add(id, new Stack()); 16 | mementos[id].Push(memento); 17 | } 18 | 19 | public Memento GetMemento(int id) => mementos[id].Pop(); 20 | } -------------------------------------------------------------------------------- /MementoPattern.Demo/MementoPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /MementoPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using MementoPattern.Demo; 2 | 3 | var employee = new Employee { Id =1, Name = "Employee", Age = 25, Phone = "123" }; 4 | var employeeManager = new EmployeeManager(); 5 | 6 | employeeManager.AddMemento(1,employee.Create()); 7 | 8 | Console.WriteLine($"Initial State: {employee.Name}, {employee.Age}, {employee.Phone}"); 9 | 10 | employee.Phone = "34567"; 11 | employeeManager.AddMemento(1, employee.Create()); 12 | Console.WriteLine($"{employee.Name}, {employee.Age}, {employee.Phone}"); 13 | 14 | employee.Age = 35; 15 | employeeManager.AddMemento(1, employee.Create()); 16 | Console.WriteLine($"{employee.Name}, {employee.Age}, {employee.Phone}"); 17 | 18 | employee.Undo(employeeManager.GetMemento(1)); 19 | employee.Undo(employeeManager.GetMemento(1)); 20 | Console.WriteLine($"{employee.Name}, {employee.Age}, {employee.Phone}"); 21 | 22 | employee.Undo(employeeManager.GetMemento(1)); 23 | Console.WriteLine($"{employee.Name}, {employee.Age}, {employee.Phone}"); -------------------------------------------------------------------------------- /ObserverPattern.Demo/Observer.cs: -------------------------------------------------------------------------------- 1 | namespace ObserverPattern.Demo; 2 | internal class Observer : IObserver 3 | { 4 | public void OnCompleted() 5 | { 6 | Console.WriteLine("Completed"); 7 | } 8 | 9 | public void OnError(Exception error) 10 | { 11 | Console.WriteLine("Error"); 12 | } 13 | 14 | public void OnNext(User value) 15 | { 16 | Console.WriteLine($"Name: {value.Name}, Age: {value.Age}"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ObserverPattern.Demo/ObserverPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /ObserverPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using ObserverPattern.Demo; 2 | 3 | var subject = new Subject("Bob", 20); 4 | var observer = new Observer(); 5 | subject.Subscribe(observer); 6 | 7 | subject.UpdateUserAge(25); 8 | await Task.Delay(1000); -------------------------------------------------------------------------------- /ObserverPattern.Demo/Subject.cs: -------------------------------------------------------------------------------- 1 | namespace ObserverPattern.Demo; 2 | 3 | internal interface ISubject 4 | { 5 | event Action UserChanged; 6 | 7 | void UpdateUserAge(int age); 8 | } 9 | 10 | internal class Subject : IObservable, IDisposable 11 | { 12 | private readonly User user; 13 | private IList> observers = new List>(); 14 | 15 | public Subject(string name, int age) 16 | { 17 | user = new User { Name = name, Age = age }; 18 | } 19 | 20 | public void Dispose() 21 | { 22 | observers.Clear(); 23 | } 24 | 25 | public IDisposable Subscribe(IObserver observer) 26 | { 27 | this.observers.Add(observer); 28 | observer.OnNext(user); 29 | return this; 30 | } 31 | 32 | public void UpdateUserAge(int age) 33 | { 34 | user.Age = age; 35 | foreach (var observer in observers) 36 | { 37 | observer.OnNext(user); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /ObserverPattern.Demo/User.cs: -------------------------------------------------------------------------------- 1 | namespace ObserverPattern.Demo; 2 | internal class User 3 | { 4 | public string Name { get; set; } 5 | public int Age { get; set; } 6 | } 7 | -------------------------------------------------------------------------------- /Pattern.Demo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FactoryMethodPattern.Demo", "FactoryMethodPattern.Demo\FactoryMethodPattern.Demo.csproj", "{48B6AA0E-6FC2-4DA3-A269-C30CE0C55ACB}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CommandPattern.Demo", "CommandPattern.Demo\CommandPattern.Demo.csproj", "{B11C91F0-C983-4BA5-BAF9-A5BEF6B19FCA}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuilderPattern.Demo", "BuilderPattern.Demo\BuilderPattern.Demo.csproj", "{C5A4E09E-7622-49A5-B588-D477247CB542}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrototypePattern.Demo", "PrototypePattern.Demo\PrototypePattern.Demo.csproj", "{26784026-F25F-4C5A-BB0E-74C47A749F74}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdapterPattern.Demo", "AdapterPattern.Demo\AdapterPattern.Demo.csproj", "{51AC736C-45EE-4E6B-86A5-1D89212DA240}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {48B6AA0E-6FC2-4DA3-A269-C30CE0C55ACB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {48B6AA0E-6FC2-4DA3-A269-C30CE0C55ACB}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {48B6AA0E-6FC2-4DA3-A269-C30CE0C55ACB}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {48B6AA0E-6FC2-4DA3-A269-C30CE0C55ACB}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {B11C91F0-C983-4BA5-BAF9-A5BEF6B19FCA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {B11C91F0-C983-4BA5-BAF9-A5BEF6B19FCA}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {B11C91F0-C983-4BA5-BAF9-A5BEF6B19FCA}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {B11C91F0-C983-4BA5-BAF9-A5BEF6B19FCA}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {C5A4E09E-7622-49A5-B588-D477247CB542}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {C5A4E09E-7622-49A5-B588-D477247CB542}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {C5A4E09E-7622-49A5-B588-D477247CB542}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {C5A4E09E-7622-49A5-B588-D477247CB542}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {26784026-F25F-4C5A-BB0E-74C47A749F74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {26784026-F25F-4C5A-BB0E-74C47A749F74}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {26784026-F25F-4C5A-BB0E-74C47A749F74}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {26784026-F25F-4C5A-BB0E-74C47A749F74}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {51AC736C-45EE-4E6B-86A5-1D89212DA240}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {51AC736C-45EE-4E6B-86A5-1D89212DA240}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {51AC736C-45EE-4E6B-86A5-1D89212DA240}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {51AC736C-45EE-4E6B-86A5-1D89212DA240}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(ExtensibilityGlobals) = postSolution 47 | SolutionGuid = {254BA296-9285-4648-8196-086108B2A6D7} 48 | EndGlobalSection 49 | EndGlobal 50 | -------------------------------------------------------------------------------- /PrototypePattern.Demo/Controllers/UserController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace PrototypePattern.Demo.Controllers; 4 | [Route("api/[controller]")] 5 | [ApiController] 6 | public class UserController : ControllerBase 7 | { 8 | private readonly IUser user; 9 | 10 | public UserController(IUser user) 11 | { 12 | this.user = user.Clone() as IUser; 13 | } 14 | 15 | [HttpGet] 16 | public IUser Get() => user; 17 | } -------------------------------------------------------------------------------- /PrototypePattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using PrototypePattern.Demo; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | 7 | builder.Services.AddControllers(); 8 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 9 | builder.Services.AddEndpointsApiExplorer(); 10 | builder.Services.AddSwaggerGen(); 11 | var user = new User("Name", "Address"); 12 | user.Age = 20; 13 | builder.Services.AddSingleton(user); 14 | 15 | var app = builder.Build(); 16 | 17 | // Configure the HTTP request pipeline. 18 | if (app.Environment.IsDevelopment()) 19 | { 20 | app.UseSwagger(); 21 | app.UseSwaggerUI(); 22 | } 23 | 24 | app.UseHttpsRedirection(); 25 | 26 | app.UseAuthorization(); 27 | 28 | app.MapControllers(); 29 | 30 | app.Run(); 31 | -------------------------------------------------------------------------------- /PrototypePattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:47638", 8 | "sslPort": 44371 9 | } 10 | }, 11 | "profiles": { 12 | "PrototypePattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7216;http://localhost:5216", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /PrototypePattern.Demo/PrototypePattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /PrototypePattern.Demo/User.cs: -------------------------------------------------------------------------------- 1 | namespace PrototypePattern.Demo; 2 | 3 | public interface IUser : ICloneable 4 | { 5 | string Name { get; } 6 | string Address { get; } 7 | int Age { set; } 8 | } 9 | 10 | public class User : IUser 11 | { 12 | private string name; 13 | private int age; 14 | private string address; 15 | 16 | public User(string name, string address) 17 | { 18 | this.name = name; 19 | this.address = address; 20 | } 21 | 22 | public string Name => name; 23 | 24 | public string Address => address; 25 | 26 | public string Details => $"User : {name}, Age: {age}, Address: {address}"; 27 | 28 | public int Age 29 | { 30 | set { age = value; } 31 | } 32 | 33 | public object Clone() 34 | { 35 | return this.MemberwiseClone(); 36 | } 37 | } -------------------------------------------------------------------------------- /PrototypePattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /PrototypePattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /ProxyPattern.Demo/ProxyPattern.Demo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32014.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProxyPattern.Demo", "ProxyPattern.Demo\ProxyPattern.Demo.csproj", "{EEFF8943-A17A-4184-B4DF-7A154BBFB299}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Weather.Forecast", "Weather.Forecast\Weather.Forecast.csproj", "{C8D964CB-1F85-4F63-8424-69CEE2C6EE8C}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {EEFF8943-A17A-4184-B4DF-7A154BBFB299}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {EEFF8943-A17A-4184-B4DF-7A154BBFB299}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {EEFF8943-A17A-4184-B4DF-7A154BBFB299}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {EEFF8943-A17A-4184-B4DF-7A154BBFB299}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {C8D964CB-1F85-4F63-8424-69CEE2C6EE8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {C8D964CB-1F85-4F63-8424-69CEE2C6EE8C}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {C8D964CB-1F85-4F63-8424-69CEE2C6EE8C}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {C8D964CB-1F85-4F63-8424-69CEE2C6EE8C}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {0915F9A0-F218-4EEB-8FFB-54ACA87DAA98} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /ProxyPattern.Demo/ProxyPattern.Demo/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Weather.Forecast; 3 | 4 | namespace ProxyPattern.Demo.Controllers; 5 | 6 | [ApiController] 7 | [Route("[controller]")] 8 | public class WeatherForecastController : ControllerBase 9 | { 10 | 11 | 12 | private readonly ILogger _logger; 13 | private readonly IWeatherProvider _weatherProvider; 14 | 15 | public WeatherForecastController(ILogger logger, 16 | IWeatherProvider weatherProvider) 17 | { 18 | _logger = logger; 19 | _weatherProvider = weatherProvider; 20 | } 21 | 22 | [HttpGet(Name = "GetWeatherForecast")] 23 | public IEnumerable Get() 24 | { 25 | return _weatherProvider.Get(4); 26 | } 27 | } -------------------------------------------------------------------------------- /ProxyPattern.Demo/ProxyPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using ProxyPattern.Demo; 2 | using Weather.Forecast; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | 7 | builder.Services.AddControllers(); 8 | builder.Services.AddEndpointsApiExplorer(); 9 | builder.Services.AddSwaggerGen(); 10 | 11 | builder.Services.AddSingleton(new WeatherProviderProxy(new WeatherProvider())); 12 | 13 | var app = builder.Build(); 14 | 15 | if (app.Environment.IsDevelopment()) 16 | { 17 | app.UseSwagger(); 18 | app.UseSwaggerUI(); 19 | } 20 | 21 | app.UseHttpsRedirection(); 22 | 23 | app.UseAuthorization(); 24 | 25 | app.MapControllers(); 26 | 27 | app.Run(); 28 | -------------------------------------------------------------------------------- /ProxyPattern.Demo/ProxyPattern.Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:23368", 8 | "sslPort": 44334 9 | } 10 | }, 11 | "profiles": { 12 | "ProxyPattern.Demo": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7103;http://localhost:5103", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ProxyPattern.Demo/ProxyPattern.Demo/ProxyPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /ProxyPattern.Demo/ProxyPattern.Demo/WeatherProviderProxy.cs: -------------------------------------------------------------------------------- 1 | using Weather.Forecast; 2 | 3 | namespace ProxyPattern.Demo; 4 | 5 | public class WeatherProviderProxy : IWeatherProvider 6 | { 7 | private readonly IWeatherProvider weatherProvider; 8 | 9 | public WeatherProviderProxy(IWeatherProvider weatherProvider) 10 | { 11 | this.weatherProvider = weatherProvider; 12 | } 13 | 14 | public IEnumerable Get(int totalCount) 15 | { 16 | if (totalCount < 2 || totalCount > 5) 17 | throw new ArgumentOutOfRangeException("totalCount", "Total count should be between two and five"); 18 | return weatherProvider.Get(totalCount); 19 | } 20 | } -------------------------------------------------------------------------------- /ProxyPattern.Demo/ProxyPattern.Demo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ProxyPattern.Demo/ProxyPattern.Demo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /ProxyPattern.Demo/Weather.Forecast/IWeatherProvider.cs: -------------------------------------------------------------------------------- 1 | namespace Weather.Forecast; 2 | 3 | public interface IWeatherProvider 4 | { 5 | IEnumerable Get(int totalCount); 6 | } -------------------------------------------------------------------------------- /ProxyPattern.Demo/Weather.Forecast/Weather.Forecast.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /ProxyPattern.Demo/Weather.Forecast/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | namespace Weather.Forecast; 2 | 3 | public class WeatherForecast 4 | { 5 | public DateTime Date { get; set; } 6 | 7 | public int TemperatureC { get; set; } 8 | 9 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 10 | 11 | public string? Summary { get; set; } 12 | } -------------------------------------------------------------------------------- /ProxyPattern.Demo/Weather.Forecast/WeatherProvider.cs: -------------------------------------------------------------------------------- 1 | namespace Weather.Forecast; 2 | 3 | public class WeatherProvider : IWeatherProvider 4 | { 5 | private static readonly string[] Summaries = new[] 6 | { 7 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 8 | }; 9 | 10 | public IEnumerable Get(int totalCount) 11 | { 12 | return Enumerable.Range(1, totalCount).Select(index => new WeatherForecast 13 | { 14 | Date = DateTime.Now.AddDays(index), 15 | TemperatureC = Random.Shared.Next(-20, 55), 16 | Summary = Summaries[Random.Shared.Next(Summaries.Length)] 17 | }).ToArray(); 18 | } 19 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Repo for Design Pattens demo -------------------------------------------------------------------------------- /StatePattern.Demo/StatePattern.Demo.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32014.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StatePattern.Demo", "StatePattern.Demo\StatePattern.Demo.csproj", "{C350397C-BA7F-45C8-8316-1C997B38BD7B}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {C350397C-BA7F-45C8-8316-1C997B38BD7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {C350397C-BA7F-45C8-8316-1C997B38BD7B}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {C350397C-BA7F-45C8-8316-1C997B38BD7B}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {C350397C-BA7F-45C8-8316-1C997B38BD7B}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {ACB89352-EE62-48D6-B5A3-2456C40BCF68} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /StatePattern.Demo/StatePattern.Demo/Car.cs: -------------------------------------------------------------------------------- 1 | namespace StatePattern.Demo; 2 | 3 | internal class Car 4 | { 5 | public enum State 6 | { 7 | Stopped, 8 | Started, 9 | Running 10 | } 11 | 12 | public enum Action 13 | { 14 | Stop, 15 | Start, 16 | Accelerate 17 | } 18 | 19 | private State state = State.Stopped; 20 | 21 | public State CurrentState { get { return state; } } 22 | 23 | public void TakeAction(Action action) 24 | { 25 | state = (state, action) switch 26 | { 27 | (State.Stopped, Action.Start) => State.Started, 28 | (State.Started, Action.Accelerate) => State.Running, 29 | (State.Started, Action.Stop) => State.Stopped, 30 | (State.Running, Action.Stop) => State.Stopped, 31 | _ => state 32 | }; 33 | } 34 | } -------------------------------------------------------------------------------- /StatePattern.Demo/StatePattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using StatePattern.Demo; 2 | 3 | var car = new Car(); 4 | 5 | Console.WriteLine($"State: {car.CurrentState}"); 6 | 7 | car.TakeAction(Car.Action.Start); 8 | Console.WriteLine($"State: {car.CurrentState}"); 9 | 10 | car.TakeAction(Car.Action.Start); 11 | Console.WriteLine($"State: {car.CurrentState}"); 12 | 13 | car.TakeAction(Car.Action.Accelerate); 14 | Console.WriteLine($"State: {car.CurrentState}"); 15 | 16 | car.TakeAction(Car.Action.Stop); 17 | Console.WriteLine($"State: {car.CurrentState}"); 18 | -------------------------------------------------------------------------------- /StatePattern.Demo/StatePattern.Demo/StatePattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /StrategyPattern.Demo/BubbleSort.cs: -------------------------------------------------------------------------------- 1 | namespace StrategyPattern.Demo; 2 | internal class BubbleSort : ISortStrategy 3 | { 4 | public int[] Sort(int[] inputArray) 5 | { 6 | var returnArray = inputArray; 7 | var length = returnArray.Length; 8 | for (int i = 0; i < length - 1; i++) 9 | for(int j = 0; j < length - i -1; j++) 10 | { 11 | if(returnArray[j] > returnArray[j + 1]) 12 | { 13 | var temp = returnArray[j]; 14 | returnArray[j] = returnArray[j + 1]; 15 | returnArray[j + 1] = temp; 16 | } 17 | } 18 | 19 | return returnArray; 20 | } 21 | } -------------------------------------------------------------------------------- /StrategyPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using StrategyPattern.Demo; 2 | 3 | var items = new[] { 88, 54, 34, 87, 15, 8, 105 }; 4 | 5 | var sortedNumbers = new SortedNumbers(new BubbleSort()); 6 | sortedNumbers.Sort(items); 7 | 8 | Console.WriteLine("======================"); 9 | 10 | sortedNumbers = new SortedNumbers(new QuickSort()); 11 | sortedNumbers.Sort(items); -------------------------------------------------------------------------------- /StrategyPattern.Demo/Sort.cs: -------------------------------------------------------------------------------- 1 | namespace StrategyPattern.Demo; 2 | 3 | internal interface ISortStrategy 4 | { 5 | int[] Sort(int[] inputArray); 6 | } 7 | 8 | internal class QuickSort : ISortStrategy 9 | { 10 | public int[] Sort(int[] inputArray) 11 | { 12 | if (inputArray == null || inputArray.Length <= 1) return inputArray; 13 | 14 | var centerIndex = inputArray.Length / 2; 15 | var centerValue = inputArray[centerIndex]; 16 | 17 | var leftPart = new List(); 18 | var rightPart = new List(); 19 | 20 | for (var i = 0; i < inputArray.Length; i++) 21 | { 22 | if (i == centerIndex) continue; 23 | if(inputArray[i] <= centerValue) 24 | leftPart.Add(inputArray[i]); 25 | else 26 | rightPart.Add(inputArray[i]); 27 | } 28 | 29 | var sorted = Sort(leftPart.ToArray()).ToList(); 30 | sorted.Add(centerValue); 31 | sorted.AddRange(Sort(rightPart.ToArray())); 32 | 33 | return sorted.ToArray(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /StrategyPattern.Demo/SortedNumbers.cs: -------------------------------------------------------------------------------- 1 | namespace StrategyPattern.Demo; 2 | 3 | internal interface ISortedNumbers 4 | { 5 | void Sort(int[] items); 6 | } 7 | 8 | internal class SortedNumbers : ISortedNumbers 9 | { 10 | private readonly ISortStrategy sortStrategy; 11 | 12 | public SortedNumbers(ISortStrategy sortStrategy) 13 | { 14 | this.sortStrategy = sortStrategy; 15 | } 16 | 17 | public void Sort(int[] items) 18 | { 19 | var sorted = sortStrategy.Sort(items); 20 | foreach (var item in sorted) 21 | Console.WriteLine(item); 22 | } 23 | } -------------------------------------------------------------------------------- /StrategyPattern.Demo/StrategyPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /TemplateMethodPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 | /* 2 | using TemplateMethodPattern.Demo.TemplateMethod; 3 | 4 | var cart = new EmailCart(); 5 | cart.Checkout(); 6 | 7 | var cart1 = new TextCart(); 8 | cart1.Checkout(); 9 | */ 10 | 11 | using TemplateMethodPattern.Demo.SOLID; 12 | 13 | var itemValidator = new ItemValidator(); 14 | var paymentExecutor = new PaymentExecutor(); 15 | 16 | var emailReciptSender = new EmailReceiptSender(); 17 | var textReceiptSender = new TextReceiptSender(); 18 | 19 | var cart = new Cart(itemValidator, paymentExecutor, emailReciptSender); 20 | cart.Checkout(); 21 | 22 | cart = new Cart(itemValidator, paymentExecutor, textReceiptSender); 23 | cart.Checkout(); -------------------------------------------------------------------------------- /TemplateMethodPattern.Demo/SOLID/Cart.cs: -------------------------------------------------------------------------------- 1 | namespace TemplateMethodPattern.Demo.SOLID; 2 | internal class Cart 3 | { 4 | private readonly IItemValidator itemValidator; 5 | private readonly IPaymentExecutor paymentExecutor; 6 | private readonly IReceiptSender receiptSender; 7 | 8 | public Cart(IItemValidator itemValidator, 9 | IPaymentExecutor paymentExecutor, 10 | IReceiptSender receiptSender) 11 | { 12 | this.itemValidator = itemValidator; 13 | this.paymentExecutor = paymentExecutor; 14 | this.receiptSender = receiptSender; 15 | } 16 | public void Checkout() 17 | { 18 | itemValidator.ValidateItem(); 19 | paymentExecutor.ExecutePayment(); 20 | receiptSender.SendReceipt(); 21 | } 22 | } -------------------------------------------------------------------------------- /TemplateMethodPattern.Demo/SOLID/IItemValidator.cs: -------------------------------------------------------------------------------- 1 | namespace TemplateMethodPattern.Demo.SOLID 2 | { 3 | public interface IItemValidator 4 | { 5 | void ValidateItem(); 6 | } 7 | 8 | public class ItemValidator : IItemValidator 9 | { 10 | public void ValidateItem() 11 | { 12 | Console.WriteLine("Item validated"); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /TemplateMethodPattern.Demo/SOLID/IPaymentExecutor.cs: -------------------------------------------------------------------------------- 1 | namespace TemplateMethodPattern.Demo.SOLID 2 | { 3 | public interface IPaymentExecutor 4 | { 5 | void ExecutePayment(); 6 | } 7 | 8 | public class PaymentExecutor : IPaymentExecutor 9 | { 10 | public void ExecutePayment() 11 | { 12 | Console.WriteLine("Payment executed"); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /TemplateMethodPattern.Demo/SOLID/IReceiptSender.cs: -------------------------------------------------------------------------------- 1 | namespace TemplateMethodPattern.Demo.SOLID 2 | { 3 | public interface IReceiptSender 4 | { 5 | void SendReceipt(); 6 | } 7 | 8 | public class EmailReceiptSender : IReceiptSender 9 | { 10 | public void SendReceipt() 11 | { 12 | Console.WriteLine("Email Sent"); 13 | } 14 | } 15 | 16 | public class TextReceiptSender : IReceiptSender 17 | { 18 | public void SendReceipt() 19 | { 20 | Console.WriteLine("Text Sent"); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /TemplateMethodPattern.Demo/TemplateMethod/Cart.cs: -------------------------------------------------------------------------------- 1 | namespace TemplateMethodPattern.Demo.TemplateMethod; 2 | internal abstract class Cart 3 | { 4 | public void Checkout() 5 | { 6 | ValidateItem(); 7 | ExecutePayment(); 8 | SendReceipt(); 9 | } 10 | 11 | protected abstract void SendReceipt(); 12 | 13 | private void ExecutePayment() 14 | { 15 | Console.WriteLine("Payment executed"); 16 | } 17 | 18 | private void ValidateItem() 19 | { 20 | Console.WriteLine("Item validated"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /TemplateMethodPattern.Demo/TemplateMethod/EmailCart.cs: -------------------------------------------------------------------------------- 1 | namespace TemplateMethodPattern.Demo.TemplateMethod; 2 | 3 | internal class EmailCart : Cart 4 | { 5 | protected override void SendReceipt() 6 | { 7 | Console.WriteLine("Email Sent"); 8 | } 9 | } 10 | 11 | internal class TextCart : Cart 12 | { 13 | protected override void SendReceipt() 14 | { 15 | Console.WriteLine("Text Sent"); 16 | } 17 | } -------------------------------------------------------------------------------- /TemplateMethodPattern.Demo/TemplateMethodPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /VisitorPattern.Demo/INotificationSender.cs: -------------------------------------------------------------------------------- 1 | namespace VisitorPattern.Demo; 2 | internal interface INotificationSender 3 | { 4 | void Send(string message); 5 | void Accept(IVisitor visitor); 6 | } 7 | -------------------------------------------------------------------------------- /VisitorPattern.Demo/IVisitor.cs: -------------------------------------------------------------------------------- 1 | namespace VisitorPattern.Demo; 2 | internal interface IVisitor 3 | { 4 | void Visit(INotificationSender notificationSender); 5 | } 6 | 7 | internal class EmailVisitor : IVisitor 8 | { 9 | public void Visit(INotificationSender notificationSender) 10 | { 11 | Console.WriteLine("Setup email"); 12 | } 13 | } 14 | 15 | internal class TextVisitor : IVisitor 16 | { 17 | public void Visit(INotificationSender notificationSender) 18 | { 19 | Console.WriteLine("Setup text"); 20 | } 21 | } 22 | 23 | internal class WebsocketVisitor : IVisitor 24 | { 25 | public void Visit(INotificationSender notificationSender) 26 | { 27 | Console.WriteLine("Setup websocket"); 28 | } 29 | } -------------------------------------------------------------------------------- /VisitorPattern.Demo/InvoiceNotificationSender.cs: -------------------------------------------------------------------------------- 1 | namespace VisitorPattern.Demo; 2 | 3 | internal class InvoiceNotificationSender : INotificationSender 4 | { 5 | public void Accept(IVisitor visitor) 6 | { 7 | visitor.Visit(this); 8 | } 9 | 10 | public void Send(string message) 11 | { 12 | Console.WriteLine($"Notification sent: {message}"); 13 | } 14 | } -------------------------------------------------------------------------------- /VisitorPattern.Demo/MarketingNotificationSender.cs: -------------------------------------------------------------------------------- 1 | namespace VisitorPattern.Demo; 2 | 3 | internal class MarketingNotificationSender : INotificationSender 4 | { 5 | public void Accept(IVisitor visitor) 6 | { 7 | visitor.Visit(this); 8 | } 9 | 10 | public void Send(string message) 11 | { 12 | Console.WriteLine($"Notification sent: {message}"); 13 | } 14 | } -------------------------------------------------------------------------------- /VisitorPattern.Demo/Program.cs: -------------------------------------------------------------------------------- 1 |  2 | using VisitorPattern.Demo; 3 | 4 | var emailVisitor = new EmailVisitor(); 5 | var textVisitor = new TextVisitor(); 6 | var websocketVisitor = new WebsocketVisitor(); 7 | 8 | var notificationSender1 = new InvoiceNotificationSender(); 9 | notificationSender1.Accept(emailVisitor); 10 | notificationSender1.Accept(textVisitor); 11 | notificationSender1.Send("Invoice"); 12 | 13 | var notificationSender2 = new MarketingNotificationSender(); 14 | notificationSender2.Accept(emailVisitor); 15 | notificationSender2.Accept(textVisitor); 16 | notificationSender2.Accept(websocketVisitor); 17 | notificationSender2.Send("Marketing"); -------------------------------------------------------------------------------- /VisitorPattern.Demo/VisitorPattern.Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | --------------------------------------------------------------------------------