├── .gitignore ├── CSharp.DesignPatterns.AbstractFactory ├── App.config ├── CSharp.DesignPatterns.AbstractFactory.csproj ├── Contracts │ └── IForwardingAgent.cs ├── Entities │ ├── Address.cs │ └── Order.cs ├── Factories │ ├── BrazilForwardingAgentFactory.cs │ ├── ForwardingAgentFactory.cs │ ├── ForwardingAgentFactoryProvider.cs │ └── USAForwardingAgentFactory.cs ├── ForwardingAgents │ ├── DHLForwardingAgent.cs │ ├── FictionalCompanyForwardingAgent.cs │ └── SedexForwardingAgent.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── Services │ └── OrderService.cs ├── CSharp.DesignPatterns.Adapter ├── App.config ├── CSharp.DesignPatterns.Adapter.csproj ├── Cache │ ├── ApplicationCacheAdapter.cs │ └── NullObjectCacheAdapter.cs ├── Contracts │ ├── ICache.cs │ └── IToDoRepository.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Repositories │ └── ToDoRepository.cs └── Services │ └── ToDoService.cs ├── CSharp.DesignPatterns.Builder ├── App.config ├── Builders │ ├── BaseWebRequestBuilder.cs │ ├── HttpWebRequestBuilder.cs │ └── ProxyHttpWebRequestBuilder.cs ├── CSharp.DesignPatterns.Builder.csproj ├── Contracts │ └── IWebRequestBuilder.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── Services │ └── SearchService.cs ├── CSharp.DesignPatterns.Composite ├── Abstractions │ └── File.cs ├── App.config ├── CSharp.DesignPatterns.Composite.csproj ├── Domain │ ├── FileComposite.cs │ ├── FolderFile.cs │ └── SystemFile.cs ├── Program.cs └── Properties │ └── AssemblyInfo.cs ├── CSharp.DesignPatterns.Decorator ├── App.config ├── CSharp.DesignPatterns.Decorator.csproj ├── Contracts │ ├── IPrice.cs │ └── IProductRepository.cs ├── Decorators │ └── ExchangeRatePriceDecorator.cs ├── Domain │ ├── ECurrency.cs │ ├── Price.cs │ └── Product.cs ├── Extensions │ └── PriceExtensions.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Repositories │ └── ProductRepository.cs └── Services │ └── ProductService.cs ├── CSharp.DesignPatterns.Observer ├── App.config ├── CSharp.DesignPatterns.Observer.csproj ├── Contracts │ ├── INewsObserver.cs │ └── NewsChangeEventArgs.cs ├── Domain │ ├── Editor.cs │ ├── News.cs │ ├── NewsSection.cs │ └── Reader.cs ├── Program.cs └── Properties │ └── AssemblyInfo.cs ├── CSharp.DesignPatterns.Proxy ├── App.config ├── CSharp.DesignPatterns.Proxy.csproj ├── Contracts │ └── IImage.cs ├── Implementations │ ├── HighResolutionImage.cs │ └── ImageProxy.cs ├── Program.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── frmImage.Designer.cs ├── frmImage.cs └── frmImage.resx ├── CSharp.DesignPatterns.Singleton ├── App.config ├── CSharp.DesignPatterns.Singleton.csproj ├── Container │ └── IoCContainer.cs ├── Contracts │ └── IToDoRepository.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── Repositories │ ├── ToDoRepositoryADO.cs │ └── ToDoRepositoryEntity.cs ├── CSharp.DesignPatterns.Strategy ├── App.config ├── CSharp.DesignPatterns.Strategy.csproj ├── Contracts │ └── IBasketDiscountStrategy.cs ├── DiscountStrategies │ ├── NoDiscountStrategy.cs │ ├── PerItemPercentualDiscountStrategy.cs │ └── PercentageDiscountStrategy.cs ├── Domain │ ├── Basket.cs │ ├── EDiscountType.cs │ └── Product.cs ├── Factories │ └── DiscountStrategyFactory.cs ├── Program.cs └── Properties │ └── AssemblyInfo.cs ├── CSharp.DesignPatterns.TemplateMethod ├── App.config ├── CSharp.DesignPatterns.TemplateMethod.csproj ├── Context │ └── ExampleDbContext.cs ├── Mapping │ ├── Base │ │ └── MappingTemplate.cs │ └── UserMapping.cs ├── Migrations │ ├── 201707051924134_Test.Designer.cs │ ├── 201707051924134_Test.cs │ ├── 201707051924134_Test.resx │ └── Configuration.cs ├── Model │ └── User.cs ├── Properties │ └── AssemblyInfo.cs └── packages.config ├── CSharp.DesignPatterns.sln ├── LICENSE └── README.md /.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 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/CSharp.DesignPatterns.AbstractFactory.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {C161C76B-3E4B-4D68-A598-32966813B3A1} 8 | Exe 9 | Properties 10 | CSharp.DesignPatterns.AbstractFactory 11 | CSharp.DesignPatterns.AbstractFactory 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 72 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Contracts/IForwardingAgent.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Entities; 2 | 3 | namespace CSharp.DesignPatterns.AbstractFactory.Contracts 4 | { 5 | /// 6 | /// Defines the contract of a forwarding agent. 7 | /// 8 | public interface IForwardingAgent 9 | { 10 | /// 11 | /// Generates a tracking id to an order. 12 | /// 13 | /// Order that needs a tracking id. 14 | void SetTrackingIdTo(Order order); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Entities/Address.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.AbstractFactory.Entities 2 | { 3 | /// 4 | /// Represents an address. 5 | /// 6 | public class Address 7 | { 8 | /// 9 | /// Country code. 10 | /// 11 | public ECountryCode CountryCode { get; private set; } 12 | 13 | public Address(ECountryCode countryCode) 14 | { 15 | CountryCode = countryCode; 16 | } 17 | } 18 | 19 | /// 20 | /// Country code. 21 | /// 22 | public enum ECountryCode : short 23 | { 24 | Brazil = 1, 25 | USA = 2 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Entities/Order.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.AbstractFactory.Entities 2 | { 3 | /// 4 | /// Represents an order requested to delivery. 5 | /// 6 | public class Order 7 | { 8 | /// 9 | /// Tracking Id generated to identify and to track the order. 10 | /// 11 | public string TrackingId { get; set; } 12 | 13 | /// 14 | /// Order's total price. 15 | /// 16 | public decimal TotalPrice { get; private set; } 17 | 18 | /// 19 | /// Order's weight. It's used to determine the forwarding agent which will delivery the order. 20 | /// 21 | public double Weight { get; private set; } 22 | 23 | /// 24 | /// Order's shipping address. 25 | /// 26 | public Address ShippingAddress { get; private set; } 27 | 28 | 29 | public Order(decimal totalPrice, double weight, Address shippingAddress) 30 | { 31 | TotalPrice = totalPrice; 32 | Weight = weight; 33 | ShippingAddress = shippingAddress; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Factories/BrazilForwardingAgentFactory.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Contracts; 2 | using CSharp.DesignPatterns.AbstractFactory.Entities; 3 | using CSharp.DesignPatterns.AbstractFactory.ForwardingAgents; 4 | 5 | namespace CSharp.DesignPatterns.AbstractFactory.Factories 6 | { 7 | /// 8 | /// Brazil forwading agents' factory. 9 | /// 10 | public class BrazilForwardingAgentFactory : ForwardingAgentFactory 11 | { 12 | /// 13 | /// Creates a forwarding agent according to an order. 14 | /// 15 | public override IForwardingAgent GetForwardingAgentFor(Order order) 16 | { 17 | if (order.Weight > 10 || order.TotalPrice > 1000) 18 | return new DHLForwardingAgent(); 19 | return new SedexForwardingAgent(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Factories/ForwardingAgentFactory.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Contracts; 2 | using CSharp.DesignPatterns.AbstractFactory.Entities; 3 | 4 | namespace CSharp.DesignPatterns.AbstractFactory.Factories 5 | { 6 | /// 7 | /// Generates forwarding agents accourding to an order. 8 | /// 9 | public abstract class ForwardingAgentFactory 10 | { 11 | /// 12 | /// Creates a forwarding agent according to an order. 13 | /// 14 | public abstract IForwardingAgent GetForwardingAgentFor(Order order); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Factories/ForwardingAgentFactoryProvider.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Entities; 2 | using System; 3 | 4 | namespace CSharp.DesignPatterns.AbstractFactory.Factories 5 | { 6 | /// 7 | /// Creates a fowarding agent factory accourding to a determined address. 8 | /// 9 | public static class ForwardingAgentFactoryProvider 10 | { 11 | /// 12 | /// Verifica o código do país do endereço para criar a factory de despachantes de correio. 13 | /// Verifies the country code and returns the respective forwarding agend factory. 14 | /// 15 | /// Address. 16 | /// Forwarding agent factory. 17 | public static ForwardingAgentFactory GetFactoryFor(Address address) 18 | { 19 | switch (address.CountryCode) 20 | { 21 | case ECountryCode.Brazil: 22 | return new BrazilForwardingAgentFactory(); 23 | case ECountryCode.USA: 24 | return new USAForwardingAgentFactory(); 25 | default: 26 | throw new NotImplementedException("There are not forwarding agents available for this country."); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Factories/USAForwardingAgentFactory.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Contracts; 2 | using CSharp.DesignPatterns.AbstractFactory.Entities; 3 | using CSharp.DesignPatterns.AbstractFactory.ForwardingAgents; 4 | 5 | namespace CSharp.DesignPatterns.AbstractFactory.Factories 6 | { 7 | /// 8 | /// USA forwading agents' factory. 9 | /// 10 | public class USAForwardingAgentFactory : ForwardingAgentFactory 11 | { 12 | /// 13 | /// Creates a forwarding agent according to an order. 14 | /// 15 | public override IForwardingAgent GetForwardingAgentFor(Order order) 16 | { 17 | if (order.Weight > 10 || order.TotalPrice > 1000) 18 | return new DHLForwardingAgent(); 19 | return new FictionalCompanyForwardingAgent(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/ForwardingAgents/DHLForwardingAgent.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Contracts; 2 | using CSharp.DesignPatterns.AbstractFactory.Entities; 3 | 4 | namespace CSharp.DesignPatterns.AbstractFactory.ForwardingAgents 5 | { 6 | /// 7 | /// DHL's forwarding agent provider. 8 | /// 9 | public class DHLForwardingAgent : IForwardingAgent 10 | { 11 | /// 12 | /// Generates a tracking id to an order. 13 | /// 14 | /// Order that needs a tracking id. 15 | public void SetTrackingIdTo(Order order) 16 | { 17 | // Hard-coded to simplify the example. 18 | order.TrackingId = "DHL-XXXX-XXXX-XXXX-XXXX"; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/ForwardingAgents/FictionalCompanyForwardingAgent.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Contracts; 2 | using CSharp.DesignPatterns.AbstractFactory.Entities; 3 | 4 | namespace CSharp.DesignPatterns.AbstractFactory.ForwardingAgents 5 | { 6 | /// 7 | /// Sedex' forwading agent service. 8 | /// 9 | public class FictionalCompanyForwardingAgent : IForwardingAgent 10 | { 11 | /// 12 | /// Generates a tracking id to an order. 13 | /// 14 | /// Order that needs a tracking id. 15 | public void SetTrackingIdTo(Order order) 16 | { 17 | // Hard-coded to simplify the example. 18 | order.TrackingId = "FCPNY-XXXX-XXXX-XXXX-XXXX"; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/ForwardingAgents/SedexForwardingAgent.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Contracts; 2 | using CSharp.DesignPatterns.AbstractFactory.Entities; 3 | 4 | namespace CSharp.DesignPatterns.AbstractFactory.ForwardingAgents 5 | { 6 | /// 7 | /// Sedex' forwading agent service. 8 | /// 9 | public class SedexForwardingAgent : IForwardingAgent 10 | { 11 | /// 12 | /// Generates a tracking id to an order. 13 | /// 14 | /// Order that needs a tracking id. 15 | public void SetTrackingIdTo(Order order) 16 | { 17 | // Hard-coded to simplify the example. 18 | order.TrackingId = "SEDEX-XXXX-XXXX-XXXX-XXXX"; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Program.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Entities; 2 | using CSharp.DesignPatterns.AbstractFactory.Services; 3 | using System; 4 | 5 | namespace CSharp.DesignPatterns.AbstractFactory 6 | { 7 | class Program 8 | { 9 | /// 10 | /// Abstract Factory pattern example. In this example, we have an ecommerce application that has products 11 | /// to be delivered in different countries. Accourding to the shipping address of an order, there are 12 | /// different forwarding agents available to that country which can delivery the requests. The agent is 13 | /// determined at runtime by some criterias, as the order's weight and total price, and the country where 14 | /// the order must be delivered. Two abstract factories are used to determine these agents, one for Brazil 15 | /// and one for USA. A factory provider, which applies the Factory Method pattern, determines the forwarding 16 | /// agent factory that will be used. To simplify the example, these fowarding agents only create a tracking 17 | /// id to every order, simulating a traceability requisite of the system. 18 | /// 19 | /// The advantage to use this approach is to separete object creation responsability in a separeted class 20 | /// that is ready to expand if we need new forwarding agents. We don't need to spend lots of time changing 21 | /// the order service structure to add new countries and agents to the application. 22 | /// 23 | static void Main(string[] args) 24 | { 25 | var brazilAddress = new Address(ECountryCode.Brazil); 26 | var usaAddress = new Address(ECountryCode.USA); 27 | 28 | var brazilOrder1 = new Order(1100M, 12, brazilAddress); 29 | var brazilOrder2 = new Order(500M, 2, brazilAddress); 30 | var usaOrder1 = new Order(1100M, 12, usaAddress); 31 | var usaOrder2 = new Order(500M, 2, usaAddress); 32 | 33 | var orderService = new OrderService(); 34 | orderService.Dispatch(brazilOrder1); 35 | orderService.Dispatch(brazilOrder2); 36 | orderService.Dispatch(usaOrder1); 37 | orderService.Dispatch(usaOrder2); 38 | 39 | Console.WriteLine("Brazil Order 1: " + brazilOrder1.TrackingId); 40 | Console.WriteLine("Brazil Order 2: " + brazilOrder2.TrackingId); 41 | Console.WriteLine("USA Order 1: " + usaOrder1.TrackingId); 42 | Console.WriteLine("USA Order 2: " + usaOrder2.TrackingId); 43 | 44 | Console.ReadKey(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.AbstractFactory")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.AbstractFactory")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("c161c76b-3e4b-4d68-a598-32966813b3a1")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.AbstractFactory/Services/OrderService.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.AbstractFactory.Contracts; 2 | using CSharp.DesignPatterns.AbstractFactory.Entities; 3 | using CSharp.DesignPatterns.AbstractFactory.Factories; 4 | 5 | namespace CSharp.DesignPatterns.AbstractFactory.Services 6 | { 7 | /// 8 | /// Service that manipulates orders to dispatch them. 9 | /// 10 | public class OrderService 11 | { 12 | /// 13 | /// Dispatches an order. 14 | /// 15 | /// Order to dispatch. 16 | public void Dispatch(Order order) 17 | { 18 | ForwardingAgentFactory factory = ForwardingAgentFactoryProvider.GetFactoryFor(order.ShippingAddress); 19 | IForwardingAgent forwardingAgent = factory.GetForwardingAgentFor(order); 20 | forwardingAgent.SetTrackingIdTo(order); 21 | // Remaining code flow. 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/CSharp.DesignPatterns.Adapter.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {34E21A8D-E0F0-4189-89D1-F635E19963CD} 8 | Exe 9 | Properties 10 | CSharp.DesignPatterns.Adapter 11 | CSharp.DesignPatterns.Adapter 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 68 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/Cache/ApplicationCacheAdapter.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Adapter.Contracts; 2 | using System; 3 | using System.Runtime.Caching; 4 | 5 | namespace CSharp.DesignPatterns.Adapter.Cache 6 | { 7 | /// 8 | /// Adapter that uses application cache to store and retrieve data. 9 | /// 10 | public class ApplicationCacheAdapter : ICache 11 | { 12 | /// 13 | /// Internally uses memory cache to store and retrieve data. 14 | /// 15 | private ObjectCache _cache; 16 | 17 | public ApplicationCacheAdapter() 18 | { 19 | _cache = new MemoryCache("memory_cache"); 20 | } 21 | 22 | /// 23 | /// Returns some data from cache. 24 | /// 25 | /// Object type to return. 26 | /// Key that identifies the object. 27 | /// Stored object. 28 | public T Get(string key) => (T)_cache.Get(key); 29 | 30 | /// 31 | /// Removes some data from cache. 32 | /// 33 | /// Key that identifies the object. 34 | public void Remove(string key) 35 | { 36 | _cache.Remove(key); 37 | } 38 | 39 | /// 40 | /// Stores some data in cache. 41 | /// 42 | /// Key to identify the object. 43 | /// Object to store. 44 | public void Store(string key, object @object) 45 | { 46 | _cache.Add(key, @object, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(30) }); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/Cache/NullObjectCacheAdapter.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Adapter.Contracts; 2 | 3 | namespace CSharp.DesignPatterns.Adapter.Cache 4 | { 5 | /// 6 | /// Null object pattern applied to cache adapter. It's used in situations we don't want to have cache. 7 | /// 8 | public class NullObjectCacheAdapter : ICache 9 | { 10 | /// 11 | /// Returns some data from cache. 12 | /// 13 | /// Object type to return. 14 | /// Key that identifies the object. 15 | /// Stored object. 16 | public T Get(string key) => default(T); 17 | 18 | /// 19 | /// Removes some data from cache. 20 | /// 21 | /// Key that identifies the object. 22 | public void Remove(string key) { } 23 | 24 | /// 25 | /// Stores some data in cache. 26 | /// 27 | /// Key to identify the object. 28 | /// Object to store. 29 | public void Store(string key, object @object) { } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/Contracts/ICache.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Adapter.Contracts 2 | { 3 | /// 4 | /// Defines the methods a cache class must have to implement. 5 | /// 6 | public interface ICache 7 | { 8 | /// 9 | /// Removes some data from cache. 10 | /// 11 | /// Key that identifies the object. 12 | void Remove(string key); 13 | 14 | /// 15 | /// Stores some data in cache. 16 | /// 17 | /// Key to identify the object. 18 | /// Object to store. 19 | void Store(string key, object @object); 20 | 21 | /// 22 | /// Returns some data from cache. 23 | /// 24 | /// Object type to return. 25 | /// Key that identifies the object. 26 | /// Stored object. 27 | T Get(string key); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/Contracts/IToDoRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace CSharp.DesignPatterns.Adapter.Contracts 4 | { 5 | /// 6 | /// Fictional entity repository. 7 | /// 8 | public interface IToDoRepository 9 | { 10 | /// 11 | /// Returns a ToDo objects list given by a fictional category name. 12 | /// 13 | /// Category name. 14 | /// Object list. 15 | IList ListByCategory(string category); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/Program.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Adapter.Cache; 2 | using CSharp.DesignPatterns.Adapter.Contracts; 3 | using CSharp.DesignPatterns.Adapter.Repositories; 4 | using CSharp.DesignPatterns.Adapter.Services; 5 | using System.Collections.Generic; 6 | using static System.Console; 7 | 8 | namespace CSharp.DesignPatterns.Adapter 9 | { 10 | class Program 11 | { 12 | /// Adapter pattern example. In this example, a cache functionality is simulated to store and to retrieve 13 | /// data for a ToDo entity listing. There are times the application have to use cache, there are times not. 14 | /// To do this, a cache interface is defined with its own cach methods. To adapt the interface to a .NET 15 | /// caching class, we create an adapter which goal is to match interface methods to .NET native methods. 16 | /// Using this approach you avoid coupling your code to specific API implementations. 17 | /// 18 | /// 19 | static void Main(string[] args) 20 | { 21 | ICache cache = new ApplicationCacheAdapter(); 22 | IToDoRepository repository = new ToDoRepository(); 23 | 24 | // First, the application cache is used to stores some data. 25 | var servico = new ToDoService(cache, repository); 26 | var lista = servico.ListByCategory("test"); 27 | WriteLine("Listing: {0}", lista[0]); 28 | WriteLine("Cached items quantity: {0}", cache.Get>("test").Count); 29 | 30 | // Then, we simulate a situation where we don't want to use cache. 31 | cache = new NullObjectCacheAdapter(); 32 | servico = new ToDoService(cache, repository); 33 | lista = servico.ListByCategory("testt"); 34 | WriteLine("Listing: {0}", lista[0]); 35 | WriteLine("Cached items quantity: {0}", cache.Get>("test") == null ? "0" : "1"); 36 | 37 | ReadKey(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.Adapter")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.Adapter")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("34e21a8d-e0f0-4189-89d1-f635e19963cd")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/Repositories/ToDoRepository.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Adapter.Contracts; 2 | using System.Collections.Generic; 3 | 4 | namespace CSharp.DesignPatterns.Adapter.Repositories 5 | { 6 | /// 7 | /// Fictional entity repository. 8 | /// 9 | public class ToDoRepository : IToDoRepository 10 | { 11 | /// 12 | /// Returns a ToDo objects list given by a fictional category name. 13 | /// 14 | /// Category name. 15 | /// Object list. 16 | public IList ListByCategory(string categoria) 17 | { 18 | return new List { "Object" }; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Adapter/Services/ToDoService.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Adapter.Contracts; 2 | using System.Collections.Generic; 3 | 4 | namespace CSharp.DesignPatterns.Adapter.Services 5 | { 6 | /// 7 | /// Service that manipulates a given entity. 8 | /// 9 | public class ToDoService 10 | { 11 | private ICache _cache; 12 | private IToDoRepository _repository; 13 | 14 | public ToDoService(ICache cache, IToDoRepository repositorio) 15 | { 16 | _cache = cache; 17 | _repository = repositorio; 18 | } 19 | 20 | /// 21 | /// Simulates a reading operation, trying to get some entities from cache and storing them if they aren't 22 | /// stored yet. 23 | /// 24 | /// A fictional parameter to identify a object by a given category. 25 | /// Object listing. 26 | public IList ListByCategory(string category) 27 | { 28 | var list = _cache.Get>(category); 29 | 30 | if (list == null) 31 | { 32 | list = _repository.ListByCategory(category); 33 | _cache.Store(category, list); 34 | } 35 | 36 | return list; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/Builders/BaseWebRequestBuilder.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Builder.Contracts; 2 | using System.Net; 3 | 4 | namespace CSharp.DesignPatterns.Builder.Builders 5 | { 6 | /// 7 | /// Base class for web request builders. 8 | /// 9 | public abstract class BaseWebRequestBuilder : IWebRequestBuilder 10 | { 11 | protected string _protocol; 12 | protected string _host; 13 | protected int _port; 14 | protected string _internalPath; 15 | protected string _queryString; 16 | protected int _timeout; 17 | 18 | /// 19 | /// Defines the request protocol (examples: HTTP, FTP, etc.). 20 | /// 21 | /// Request protocol. 22 | /// Builder. 23 | public abstract IWebRequestBuilder Protocol(string protocol); 24 | 25 | /// 26 | /// Address to send the request. 27 | /// 28 | /// Address. 29 | /// Builder. 30 | public abstract IWebRequestBuilder Host(string host); 31 | 32 | /// 33 | /// Request port (example: 80). 34 | /// 35 | /// Request port. 36 | /// Builder. 37 | public abstract IWebRequestBuilder Port(int port); 38 | 39 | /// 40 | /// Defines the internal path in the address to send the request. 41 | /// 42 | /// Internal path. 43 | /// Builder. 44 | public abstract IWebRequestBuilder InternalPath(string internalPath); 45 | 46 | /// 47 | /// Defines the query string to send. 48 | /// 49 | /// Query string. 50 | /// Builder. 51 | public abstract IWebRequestBuilder QueryString(string queryString); 52 | 53 | /// 54 | /// Defines the request timeout. 55 | /// 56 | /// Request timeout. 57 | /// Builder. 58 | public abstract IWebRequestBuilder Timeout(int timeout); 59 | 60 | /// 61 | /// Creates the web request. 62 | /// 63 | /// WebRequest. 64 | public abstract WebRequest Build(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/Builders/HttpWebRequestBuilder.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Builder.Contracts; 2 | using System.Net; 3 | 4 | namespace CSharp.DesignPatterns.Builder.Builders 5 | { 6 | /// 7 | /// HTTP web request builder. 8 | /// 9 | public class HttpWebRequestBuilder : BaseWebRequestBuilder 10 | { 11 | /// 12 | /// Defines the request protocol (examples: HTTP, FTP, etc.). 13 | /// 14 | /// Request protocol. 15 | /// Builder. 16 | public override IWebRequestBuilder Protocol(string protocol) 17 | { 18 | _protocol = protocol; 19 | return this; 20 | } 21 | 22 | /// 23 | /// Address to send the request. 24 | /// 25 | /// Address. 26 | /// Builder. 27 | public override IWebRequestBuilder Host(string host) 28 | { 29 | _host = host; 30 | return this; 31 | } 32 | 33 | /// 34 | /// Request port (example: 80). 35 | /// 36 | /// Request port. 37 | /// Builder. 38 | public override IWebRequestBuilder Port(int port) 39 | { 40 | _port = port; 41 | return this; 42 | } 43 | 44 | /// 45 | /// Defines the internal path in the address to send the request. 46 | /// 47 | /// Internal path. 48 | /// Builder. 49 | public override IWebRequestBuilder InternalPath(string internalPath) 50 | { 51 | _internalPath = internalPath; 52 | return this; 53 | } 54 | 55 | /// 56 | /// Defines the query string to send. 57 | /// 58 | /// Query string. 59 | /// Builder. 60 | public override IWebRequestBuilder QueryString(string queryString) 61 | { 62 | _queryString = queryString; 63 | return this; 64 | } 65 | 66 | /// 67 | /// Defines the request timeout. 68 | /// 69 | /// Request timeout. 70 | /// Builder. 71 | public override IWebRequestBuilder Timeout(int timeout) 72 | { 73 | _timeout = timeout; 74 | return this; 75 | } 76 | 77 | /// 78 | /// Método a ser executado antes de retornar a instância da requisição web no método "Build". 79 | /// Method to execute while web request is created ("Build"). 80 | /// 81 | /// Created web request. 82 | protected virtual void OnBuild(HttpWebRequest httpWebRequest) { } 83 | 84 | /// 85 | /// Creates the web request. 86 | /// 87 | /// WebRequest. 88 | public override WebRequest Build() 89 | { 90 | var uri = $"{_protocol}://{_host}:{_port}/{_internalPath}?{_queryString}"; 91 | var httpWebRequest = WebRequest.CreateHttp(uri); 92 | httpWebRequest.Timeout = _timeout; 93 | OnBuild(httpWebRequest); 94 | return httpWebRequest; 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/Builders/ProxyHttpWebRequestBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | 3 | namespace CSharp.DesignPatterns.Builder.Builders 4 | { 5 | /// 6 | /// HTTP request builder for requests which need a proxy. 7 | /// 8 | public class ProxyHttpWebRequestBuilder : HttpWebRequestBuilder 9 | { 10 | /// 11 | /// Proxy address. 12 | /// 13 | private string _proxy = null; 14 | 15 | /// 16 | /// Username for proxy authentication. 17 | /// 18 | private string _userName = null; 19 | 20 | /// 21 | /// Password for proxy authentication. 22 | /// 23 | private string _password = null; 24 | 25 | public ProxyHttpWebRequestBuilder(string proxy) 26 | { 27 | _proxy = proxy; 28 | } 29 | 30 | public ProxyHttpWebRequestBuilder(string proxy, string userName, string password) : this(proxy) 31 | { 32 | _userName = userName; 33 | _password = password; 34 | } 35 | 36 | /// 37 | /// Overrides "OnBuild" method to define the proxy on web request creation. 38 | /// 39 | /// Web request. 40 | protected override void OnBuild(HttpWebRequest httpWebRequest) 41 | { 42 | httpWebRequest.Proxy = new WebProxy(_proxy); 43 | if (_userName != null) 44 | { 45 | httpWebRequest.Proxy.Credentials = new NetworkCredential 46 | { 47 | UserName = _userName, 48 | Password = _password 49 | }; 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/CSharp.DesignPatterns.Builder.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {AD6032EA-35B4-4AFF-B555-8C8934CE88E8} 8 | Exe 9 | Properties 10 | CSharp.DesignPatterns.Builder 11 | CSharp.DesignPatterns.Builder 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 65 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/Contracts/IWebRequestBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | 3 | namespace CSharp.DesignPatterns.Builder.Contracts 4 | { 5 | /// 6 | /// Defines the contract of a builder that creates web requests. 7 | /// 8 | public interface IWebRequestBuilder 9 | { 10 | /// 11 | /// Defines the request protocol (examples: HTTP, FTP, etc.). 12 | /// 13 | /// Request protocol. 14 | /// Builder. 15 | IWebRequestBuilder Protocol(string protocol); 16 | 17 | /// 18 | /// Address to send the request. 19 | /// 20 | /// Address. 21 | /// Builder. 22 | IWebRequestBuilder Host(string host); 23 | 24 | /// 25 | /// Request port (example: 80). 26 | /// 27 | /// Request port. 28 | /// Builder. 29 | IWebRequestBuilder Port(int port); 30 | 31 | /// 32 | /// Defines the internal path in the address to send the request. 33 | /// 34 | /// Internal path. 35 | /// Builder. 36 | IWebRequestBuilder InternalPath(string internalPath); 37 | 38 | /// 39 | /// Defines the query string to send. 40 | /// 41 | /// Query string. 42 | /// Builder. 43 | IWebRequestBuilder QueryString(string queryString); 44 | 45 | /// 46 | /// Defines the request timeout. 47 | /// 48 | /// Request timeout. 49 | /// Builder. 50 | IWebRequestBuilder Timeout(int timeout); 51 | 52 | /// 53 | /// Creates the web request. 54 | /// 55 | /// WebRequest. 56 | WebRequest Build(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/Program.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Builder.Builders; 2 | using CSharp.DesignPatterns.Builder.Services; 3 | using System; 4 | using System.Threading.Tasks; 5 | 6 | namespace CSharp.DesignPatterns.Builder 7 | { 8 | class Program 9 | { 10 | /// Builder pattern example. In this example, we need to create web requests to get content from diffent 11 | /// APIs. A builder interface was created to define how web requests will be created, allowing developers 12 | /// to use methods to set parameters that will be used by the request. This interface has two implementations: 13 | /// - HttpWebRequestBuilder: creates a web request that uses the HTTP protocol to query data sources; 14 | /// - ProxyHttpWebRequest: same as above, but lets the developer define a proxy for the connection. 15 | /// 16 | /// The advantage of this approach is to give developers a simple API to create objects that have many 17 | /// arguments to define. Defining these arguments in the constructor would make code hard to read and 18 | /// hard to maintain in case of need to use new parameters. 19 | /// 20 | /// 21 | static void Main(string[] args) 22 | { 23 | Task.Run(async () => 24 | { 25 | var searchService = new SearchService(new HttpWebRequestBuilder()); 26 | var results = await searchService.GetResultsAsync("ajax.googleapis.com", 27 | "ajax/services/search/web", 28 | "v=1.0&q=evgomes"); 29 | 30 | searchService.Builder = new ProxyHttpWebRequestBuilder("http://proxy.proxyaddress.com", "SomeUserName", "SomePassword"); 31 | var proxyResults = await searchService.GetResultsAsync("ajax.googleapis.com", 32 | "ajax/services/search/web", 33 | "v=1.0&q=evgomes"); 34 | 35 | Console.WriteLine($"Results from first request: {results}\n\n"); 36 | Console.WriteLine($"Results from second request: {proxyResults}\n\n"); 37 | }); 38 | 39 | Console.ReadKey(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.Builder")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.Builder")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("ad6032ea-35b4-4aff-b555-8c8934ce88e8")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Builder/Services/SearchService.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Builder.Contracts; 2 | using System.IO; 3 | using System.Net; 4 | using System.Threading.Tasks; 5 | 6 | namespace CSharp.DesignPatterns.Builder.Services 7 | { 8 | /// 9 | /// Search service that uses web requests to query data sources. 10 | /// 11 | public class SearchService 12 | { 13 | /// 14 | /// Builder to create web requests. 15 | /// 16 | public IWebRequestBuilder Builder { get; set; } 17 | 18 | public SearchService(IWebRequestBuilder builder) 19 | { 20 | Builder = builder; 21 | } 22 | 23 | /// 24 | /// Returns all results of a query executed with an HTTP request. 25 | /// 26 | /// Search address. 27 | /// Internal path to query. 28 | /// Request query string. 29 | /// Results from data source. 30 | public async Task GetResultsAsync(string address, string internalPath, string queryString) 31 | { 32 | var request = Construct(address, internalPath, queryString); 33 | var response = await request.GetResponseAsync(); 34 | 35 | using (var reader = new StreamReader(response.GetResponseStream())) 36 | { 37 | return await reader.ReadToEndAsync(); 38 | } 39 | } 40 | 41 | /// 42 | /// Creates an HTTP web request using the builder. 43 | /// 44 | /// Request address. 45 | /// Internal path. 46 | /// Query string. 47 | /// WebRequest. 48 | private WebRequest Construct(string address, string internalPath, string queryString) 49 | { 50 | return Builder.Protocol("http") 51 | .Host(address) 52 | .Port(80) 53 | .InternalPath(internalPath) 54 | .QueryString(queryString) 55 | .Timeout(30) 56 | .Build(); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Composite/Abstractions/File.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Composite.Abstractions 2 | { 3 | /// 4 | /// Represents a file on disk. 5 | /// 6 | public abstract class File 7 | { 8 | /// 9 | /// File's name. 10 | /// 11 | public string Name { get; private set; } 12 | 13 | /// 14 | /// File level on folders tree. 15 | /// 16 | public int Level { get; set; } 17 | 18 | public File(string name) 19 | { 20 | Name = name; 21 | } 22 | 23 | /// 24 | /// Inserts a file inside other. This is used by folders and compressed files. 25 | /// 26 | /// File to add inside this one. 27 | public abstract void Add(File file); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Composite/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Composite/CSharp.DesignPatterns.Composite.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {28E77374-99A3-4787-AE36-F1552A47F3E6} 8 | Exe 9 | Properties 10 | CSharp.DesignPatterns.Composite 11 | CSharp.DesignPatterns.Composite 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 64 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Composite/Domain/FileComposite.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Composite.Abstractions; 2 | using System.Collections.Generic; 3 | 4 | namespace CSharp.DesignPatterns.Composite.Domain 5 | { 6 | /// 7 | /// Represents a file that allows other files to be placed within it. Examples: folder, compressed files. 8 | /// 9 | public abstract class FileComposite : File 10 | { 11 | /// 12 | /// Internal files list. Represents all files inside the folder or compressed file. 13 | /// 14 | private IList _files; 15 | 16 | public FileComposite(string nome) : base(nome) 17 | { 18 | _files = new List(); 19 | } 20 | 21 | /// 22 | /// Add a file to folder or compressed folder. 23 | /// 24 | /// File to add. 25 | public override void Add(File file) 26 | { 27 | _files.Add(file); 28 | } 29 | 30 | /// 31 | /// Shows the folder or compressed file name and all files contained within it. 32 | /// 33 | /// File listing. 34 | public override string ToString() 35 | { 36 | // Uses the level of each file to show in what level they are accourding to its respective folder. 37 | string output = string.Format("{0}{1}\n", new string('-', Level), Name); 38 | 39 | foreach (var file in _files) 40 | { 41 | file.Level += Level + 2; 42 | output = string.Concat(output, file.ToString()); 43 | } 44 | 45 | Level = 0; 46 | return output; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Composite/Domain/FolderFile.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Composite.Domain 2 | { 3 | /// 4 | /// Represents a folder. 5 | /// 6 | public sealed class FolderFile : FileComposite 7 | { 8 | public FolderFile(string name) : base(name) { } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Composite/Domain/SystemFile.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Composite.Abstractions; 2 | 3 | namespace CSharp.DesignPatterns.Composite.Domain 4 | { 5 | /// 6 | /// Represents a system file that has no files within it. Examples: .docx, .pdf, .jpg. 7 | /// 8 | public sealed class SystemFile : File 9 | { 10 | public SystemFile(string nome) : base(nome) { } 11 | 12 | /// 13 | /// Operação de adição de um arquivo a outro. 14 | /// Add operation. A common file doesn't allow other files to be added within it, so this operation 15 | /// has no implementation. 16 | /// 17 | /// 18 | public override void Add(File file) { } 19 | 20 | /// 21 | /// Show file's name. 22 | /// 23 | /// File's name. 24 | public override string ToString() 25 | { 26 | string saida = string.Format("{0}{1}\n", new string('-', Level), Name); 27 | Level = 0; 28 | return saida; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Composite/Program.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Composite.Domain; 2 | using System; 3 | 4 | namespace CSharp.DesignPatterns.Composite 5 | { 6 | /// 7 | /// The composite pattern is applied here to satisfy these requisites, allowing folders and compressed files 8 | /// to have other files inside it and allowing the recursive operation of showing all files to work. 9 | /// 10 | /// The goal of composite pattern is exactly it, to work with items in tree structures in a way encapsulation 11 | /// and inheritance aren't broken. Of course there are different approaches that could have been used here, 12 | /// but this was done this way to exemplify the pattern. 13 | /// 14 | class Program 15 | { 16 | static void Main(string[] args) 17 | { 18 | var arquivoXls = new SystemFile("graph.xls"); 19 | var arquivoDoc = new SystemFile("document.doc"); 20 | var arquivoPdf = new SystemFile("pdfdocument.pdf"); 21 | var arquivoPpt = new SystemFile("lecture.ppt"); 22 | var arquivoPng = new SystemFile("image.png"); 23 | 24 | var pastaNivel3 = new FolderFile("Level 2 Folder"); 25 | pastaNivel3.Add(arquivoXls); 26 | pastaNivel3.Add(arquivoDoc); 27 | pastaNivel3.Add(arquivoPdf); 28 | 29 | var pastaNivel2 = new FolderFile("Level 1 Folder"); 30 | pastaNivel2.Add(arquivoPpt); 31 | pastaNivel2.Add(pastaNivel3); 32 | 33 | var pastaRaiz = new FolderFile("Root Folder"); 34 | pastaRaiz.Add(arquivoPng); 35 | pastaRaiz.Add(pastaNivel2); 36 | 37 | Console.WriteLine("------Files structure from root folder------\n\n"); 38 | Console.WriteLine(pastaRaiz.ToString()); 39 | 40 | Console.WriteLine("\n\n------Files structure from foler level 1-----\n\n"); 41 | Console.WriteLine(pastaNivel2.ToString()); 42 | 43 | Console.WriteLine("\n\n------Files structure from folder level 2------\n\n"); 44 | Console.WriteLine(pastaNivel3.ToString()); 45 | 46 | Console.ReadKey(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Composite/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.Composite")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.Composite")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("28e77374-99a3-4787-ae36-f1552a47f3e6")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/CSharp.DesignPatterns.Decorator.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {137264F8-34E7-4512-B309-1CED265504C3} 8 | Exe 9 | Properties 10 | CSharp.DesignPatterns.Decorator 11 | CSharp.DesignPatterns.Decorator 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 70 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Contracts/IPrice.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Decorator.Contracts 2 | { 3 | /// 4 | /// Defines a price for the system. 5 | /// 6 | public interface IPrice 7 | { 8 | /// 9 | /// Value. 10 | /// 11 | decimal Coast { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Contracts/IProductRepository.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Decorator.Domain; 2 | using System.Collections.Generic; 3 | 4 | namespace CSharp.DesignPatterns.Decorator.Contracts 5 | { 6 | /// 7 | /// Products repository. 8 | /// 9 | public interface IProductRepository 10 | { 11 | /// 12 | /// Lists all products from a data source. 13 | /// 14 | /// Products list. 15 | IEnumerable List(); 16 | } 17 | } -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Decorators/ExchangeRatePriceDecorator.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Decorator.Contracts; 2 | 3 | namespace CSharp.DesignPatterns.Decorator.Decorators 4 | { 5 | /// 6 | /// Represents a product price, applying an exchange rate accourding to a specific currency. 7 | /// Example: at the momement this project was coded, "US$ 1" was equivalent to approximately "R$ 3.30". 8 | /// 9 | public class ExchangeRatePriceDecorator : IPrice 10 | { 11 | /// 12 | /// Product's original price. 13 | /// 14 | private IPrice _price; 15 | 16 | /// 17 | /// Exchange rate applied over the original price. 18 | /// 19 | private decimal _exchangeRate; 20 | 21 | public ExchangeRatePriceDecorator(IPrice price, decimal exchangeRate) 22 | { 23 | _price = price; 24 | _exchangeRate = exchangeRate; 25 | } 26 | 27 | /// 28 | /// Coast accourding to an exchange rate. 29 | /// 30 | public decimal Coast 31 | { 32 | get { return _price.Coast * _exchangeRate; } 33 | set { _price.Coast = value; } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Domain/ECurrency.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Decorator.Domain 2 | { 3 | /// 4 | /// Represents an exchange rate; 5 | /// 6 | public enum ECurrency : byte 7 | { 8 | Real = 1, // Brazilian currency 9 | Dolar = 2 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Domain/Price.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Decorator.Contracts; 2 | 3 | namespace CSharp.DesignPatterns.Decorator.Domain 4 | { 5 | /// 6 | /// Represent a product price. 7 | /// 8 | public class Price : IPrice 9 | { 10 | private decimal _coast; 11 | 12 | /// 13 | /// Coast. 14 | /// 15 | public decimal Coast 16 | { 17 | get { return _coast; } 18 | set { _coast = value; } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Domain/Product.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Decorator.Contracts; 2 | 3 | namespace CSharp.DesignPatterns.Decorator.Domain 4 | { 5 | /// 6 | /// Represents a product. 7 | /// 8 | public class Product 9 | { 10 | /// 11 | /// Product's price. 12 | /// 13 | public IPrice Price { get; set; } 14 | 15 | public Product(IPrice price) 16 | { 17 | Price = price; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Extensions/PriceExtensions.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Decorator.Decorators; 2 | using CSharp.DesignPatterns.Decorator.Domain; 3 | using System.Collections.Generic; 4 | 5 | namespace CSharp.DesignPatterns.Decorator.Extensions 6 | { 7 | /// 8 | /// Price extensions. 9 | /// 10 | public static class PriceExtensions 11 | { 12 | /// 13 | /// Applies an exchange rate over the price of a products enumeration. 14 | /// 15 | /// Products enumeration. 16 | /// Exchange rate to apply over all prices. 17 | public static void ApplyExchangeRate(this IEnumerable products, decimal exchangeRate) 18 | { 19 | foreach (var product in products) 20 | { 21 | var originalPrice = product.Price; 22 | product.Price = new ExchangeRatePriceDecorator(originalPrice, exchangeRate); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Program.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Decorator.Domain; 2 | using CSharp.DesignPatterns.Decorator.Repositories; 3 | using CSharp.DesignPatterns.Decorator.Services; 4 | using System; 5 | using System.Linq; 6 | 7 | namespace CSharp.DesignPatterns.Decorator 8 | { 9 | class Program 10 | { 11 | /// 12 | /// Decorator pattern example. In this example, we have an ecommerce application that deals with costumers 13 | /// from different countries. Accourding to each country, a product's price is shown with a differente value, 14 | /// because of currency. To show the price accourding to a currency, a decorator is created to convert the 15 | /// original value, in US$, to a different rate. 16 | /// 17 | /// There are a lot of approaches you can use in a situation like that, but this solution was chosen to show 18 | /// how a decorator can extends code functionality for existing classes avoiding to break encapsulation. 19 | /// It's a usefull approach when you need to extend an API functionality, but you don't have access to its 20 | /// code. 21 | /// 22 | /// 23 | static void Main(string[] args) 24 | { 25 | var service = new ProductService(new ProductRepository()); 26 | 27 | // First shows each product's price in US$. 28 | var products = service.ListByCurrency(ECurrency.Dolar); 29 | for (int index = 0; index < products.Count(); index++) 30 | { 31 | Console.WriteLine($"Product {index}: US$ {products.ElementAt(index).Price.Coast}"); 32 | } 33 | 34 | Console.WriteLine(); 35 | 36 | // Then shows each product's price in R$. 37 | products = service.ListByCurrency(ECurrency.Real); 38 | for (int index = 0; index < products.Count(); index++) 39 | { 40 | Console.WriteLine($"Product {index}: R$ {products.ElementAt(index).Price.Coast}"); 41 | } 42 | 43 | Console.ReadKey(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.Decorator")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.Decorator")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("137264f8-34e7-4512-b309-1ced265504c3")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Repositories/ProductRepository.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Decorator.Contracts; 2 | using CSharp.DesignPatterns.Decorator.Domain; 3 | using System.Collections.Generic; 4 | 5 | namespace CSharp.DesignPatterns.Decorator.Repositories 6 | { 7 | public class ProductRepository : IProductRepository 8 | { 9 | /// 10 | /// Products repository. 11 | /// 12 | /// Products. 13 | public IEnumerable List() 14 | { 15 | var products = new List(); 16 | for (int index = 0; index <= 10; index++) 17 | { 18 | var price = new Price(); 19 | price.Coast = index; 20 | products.Add(new Product(price)); 21 | } 22 | return products; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Decorator/Services/ProductService.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Decorator.Contracts; 2 | using CSharp.DesignPatterns.Decorator.Domain; 3 | using CSharp.DesignPatterns.Decorator.Extensions; 4 | using System.Collections.Generic; 5 | 6 | namespace CSharp.DesignPatterns.Decorator.Services 7 | { 8 | /// 9 | /// Service that manages products. 10 | /// 11 | public class ProductService 12 | { 13 | private IProductRepository _repositorio; 14 | 15 | public ProductService(IProductRepository repositorio) 16 | { 17 | _repositorio = repositorio; 18 | } 19 | 20 | /// 21 | /// Returns a products list, where all producs have a price accourding to a currency. 22 | /// 23 | /// Currency that determines each product price. 24 | /// Products. 25 | public IEnumerable ListByCurrency(ECurrency currency) 26 | { 27 | var products = _repositorio.List(); 28 | if (currency == ECurrency.Real) 29 | products.ApplyExchangeRate(3.30M); 30 | return products; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/CSharp.DesignPatterns.Observer.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {BAB7507E-5F86-4EF0-A295-5E389DDE5224} 8 | Exe 9 | Properties 10 | CSharp.DesignPatterns.Observer 11 | CSharp.DesignPatterns.Observer 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 66 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/Contracts/INewsObserver.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Observer.Contracts 2 | { 3 | /// 4 | /// Defines a contract that an news' event observer must have in the system. 5 | /// This interface is implemented by the reader class, and asserts all readers will be notified every time a news is created 6 | /// or when an existing one is edited. 7 | /// 8 | public interface INewsObserver 9 | { 10 | /// 11 | /// Reader's name. 12 | /// 13 | string Name { get; set; } 14 | 15 | /// 16 | /// Dispatched notification when a news change or a new one is created. 17 | /// 18 | /// Performed the action that resulted in the notification. 19 | /// Event argument that constains the news item. 20 | void Notify(object sender, NewsChangeEventArgs e); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/Contracts/NewsChangeEventArgs.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Observer.Domain; 2 | using System; 3 | 4 | namespace CSharp.DesignPatterns.Observer.Contracts 5 | { 6 | /// 7 | /// Event argument used to pass information of a news being created or edited. 8 | /// 9 | public class NewsChangeEventArgs : EventArgs 10 | { 11 | /// 12 | /// News that was created or edited. 13 | /// 14 | public News News { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/Domain/Editor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CSharp.DesignPatterns.Observer.Domain 4 | { 5 | /// 6 | /// Person responsible for creating and editing news. 7 | /// 8 | public class Editor 9 | { 10 | /// 11 | /// Editor's name. 12 | /// 13 | public string Name { get; set; } 14 | 15 | /// 16 | /// This method creates a new news item and register it to a newspaper section. 17 | /// 18 | /// Section where the news should be registered. 19 | /// News' title. 20 | /// News' synthesis. 21 | /// Created news. 22 | public News RegisterNewsFor(NewsSection newsSection, string title, string synthesis) 23 | { 24 | var news = new News 25 | { 26 | Editor = this, 27 | PublishDate = DateTime.Now, 28 | Title = title, 29 | Synthesis = synthesis 30 | }; 31 | 32 | newsSection.RegisterNews(news); 33 | return news; 34 | } 35 | 36 | /// 37 | /// Updates a news for a section. 38 | /// 39 | /// Section where the news should be updated. 40 | /// News that need to be updated. 41 | public void UpdateNewsFor(NewsSection newsSection, News news) 42 | { 43 | news.EditDate = DateTime.Now; 44 | news.UpdateEditor = this; 45 | newsSection.RegisterNews(news); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/Domain/News.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CSharp.DesignPatterns.Observer.Domain 4 | { 5 | public class News 6 | { 7 | /// 8 | /// News' title. 9 | /// 10 | public string Title { get; set; } 11 | 12 | /// 13 | /// Publish date. 14 | /// 15 | public DateTime PublishDate { get; set; } 16 | 17 | /// 18 | /// Date when the news was edited the last time. 19 | /// 20 | public DateTime? EditDate { get; set; } 21 | 22 | /// 23 | /// News' synthesis. 24 | /// 25 | public string Synthesis { get; set; } 26 | 27 | /// 28 | /// Person who published the news. 29 | /// 30 | public Editor Editor { get; set; } 31 | 32 | /// 33 | /// Person that edited the news the last time. 34 | /// 35 | public Editor UpdateEditor { get; set; } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/Domain/NewsSection.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Observer.Contracts; 2 | using System; 3 | 4 | namespace CSharp.DesignPatterns.Observer.Domain 5 | { 6 | /// 7 | /// This class represents a section of a journal. Examples: politics section, economics section. 8 | /// 9 | public class NewsSection 10 | { 11 | /// 12 | /// Section's name. 13 | /// 14 | public string Name { get; private set; } 15 | 16 | public NewsSection(string name) 17 | { 18 | Name = name; 19 | } 20 | 21 | /// 22 | /// News change event handler. Used to assign notify methods of section's readers. 23 | /// 24 | protected EventHandler Change; 25 | 26 | /// 27 | /// Invokes all methods assigned to "Change" event handler, in order to notify all readers about updates. 28 | /// 29 | /// Update event. 30 | protected virtual void OnChange(NewsChangeEventArgs e) 31 | { 32 | Change?.Invoke(this, e); 33 | } 34 | 35 | /// 36 | /// Registers a news reader as a section's reader. 37 | /// 38 | /// News reader. 39 | public void RegisterReader(INewsObserver reader) 40 | { 41 | Change += reader.Notify; 42 | Console.WriteLine($"{reader.Name} registered as a {Name} section's reader.\n"); 43 | } 44 | 45 | /// 46 | /// Removes a news reader from section's reader list. 47 | /// 48 | /// News reader. 49 | public void RemoveReader(INewsObserver reader) 50 | { 51 | Change -= reader.Notify; 52 | Console.WriteLine($"{reader.Name} removed from {Name} section's reader list.\n"); 53 | } 54 | 55 | /// 56 | /// Registers a news in this newspaper section and notify all readers about the update. 57 | /// In a real application, it probably would perfom some database operations and only after that readers would be 58 | /// notified of the changes. 59 | /// 60 | /// News to register. 61 | public void RegisterNews(News news) 62 | { 63 | OnChange(new NewsChangeEventArgs { News = news }); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/Domain/Reader.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Observer.Contracts; 2 | using System; 3 | 4 | namespace CSharp.DesignPatterns.Observer.Domain 5 | { 6 | public class Reader : INewsObserver 7 | { 8 | /// 9 | /// Reader's name. 10 | /// 11 | public string Name { get; set; } 12 | 13 | /// 14 | /// Notifies the reader when an editor register a new news item in a section or when an existing one is edited. 15 | /// In a real application, it could be an e-mail, in a web application, or a notification, in a mobile application. 16 | /// 17 | /// Action performer. 18 | /// Event argument. 19 | public void Notify(object sender, NewsChangeEventArgs e) 20 | { 21 | if (e.News.EditDate != null) 22 | Console.WriteLine($"Hello \"{Name}\". The news \"{e.News.Title}\" was edited in {e.News.EditDate.Value.ToLongDateString()} by {e.News.UpdateEditor.Name}.\nSynthesis: {e.News.Synthesis}\n"); 23 | else 24 | Console.WriteLine($"Hello \"{Name}\". New news item: \"{e.News.Title}\".\n Registered in {e.News.PublishDate.ToLongDateString()} by {e.News.Editor.Name}.\nSynthesis: {e.News.Synthesis}\n"); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/Program.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Observer.Domain; 2 | using System; 3 | 4 | namespace CSharp.DesignPatterns.Observer 5 | { 6 | class Program 7 | { 8 | /// 9 | /// Observer Pattern example. In this example, we have a digital newspaper, which contains two sections: 10 | /// sports and politics. There are specific editors to every section, as well as readers interested in 11 | /// receiving notifications about new news items and changes on these news, according to sections they 12 | /// are interested. 13 | /// 14 | /// The observer is applied to notify all readers about changes and new items registered to sections they 15 | /// are interested in. 16 | /// 17 | /// In a real world application, you could apply this pattern to send e-mails for employees responsible 18 | /// for different areas of a company, when an item is sold, a costumer requests a product, etc. 19 | /// 20 | /// 21 | static void Main(string[] args) 22 | { 23 | // Create all sections 24 | var sportsSection = new NewsSection("Sports Section"); 25 | var politicsSection = new NewsSection("Politics Section"); 26 | 27 | // Create the sections' readers. 28 | var sportsSectionReader = new Reader { Name = "Sports Reader" }; 29 | var politicsSectionReader = new Reader { Name = "Politics Reader" }; 30 | var bothSectionsReader = new Reader { Name = "Both Sections Reader" }; 31 | 32 | // Create the editors. 33 | var sportsEditor = new Editor { Name = "Sports Editor" }; 34 | var politicsEditor = new Editor { Name = "Politics Editor" }; 35 | 36 | // Register all readers to the respective section. 37 | sportsSection.RegisterReader(sportsSectionReader); 38 | sportsSection.RegisterReader(bothSectionsReader); 39 | politicsSection.RegisterReader(politicsSectionReader); 40 | politicsSection.RegisterReader(bothSectionsReader); 41 | 42 | // Two diffente news are created, registered to a section, and one on them is changed, so the readers receive notifications about the actions performed. 43 | var sportNews = sportsEditor.RegisterNewsFor(sportsSection, "Fictional Player is the new reinforcement of Fictional Team.", "Fictional Team has bought all rights from Other Team last week to have Fictional Player for two years."); 44 | var politicsNews = politicsEditor.RegisterNewsFor(politicsSection, "City hall starts new building construction on fictional address.", "Fictional City's city hall has started the construction of a new building..."); 45 | 46 | politicsNews.Synthesis = "Update: Fictional City's mayor will see the construction tomorrow, about 08:00 AM..."; 47 | politicsEditor.UpdateNewsFor(politicsSection, politicsNews); 48 | 49 | // Remove the reader interested in both sections from sports section, and then change the sports news to verify how the notification is handled. 50 | sportsSection.RemoveReader(bothSectionsReader); 51 | sportNews.Title = "Fictional Player surprises supporters on accepting proposal from Fictional Team."; 52 | sportsEditor.UpdateNewsFor(sportsSection, sportNews); 53 | 54 | Console.ReadKey(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Observer/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.Observer")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.Observer")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("bab7507e-5f86-4ef0-a295-5e389dde5224")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/CSharp.DesignPatterns.Proxy.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {F8DAE7A9-E27B-4198-B143-67E5D24B2753} 8 | WinExe 9 | Properties 10 | CSharp.DesignPatterns.Proxy 11 | CSharp.DesignPatterns.Proxy 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | Form 52 | 53 | 54 | frmImage.cs 55 | 56 | 57 | 58 | 59 | 60 | 61 | frmImage.cs 62 | 63 | 64 | ResXFileCodeGenerator 65 | Resources.Designer.cs 66 | Designer 67 | 68 | 69 | True 70 | Resources.resx 71 | 72 | 73 | SettingsSingleFileGenerator 74 | Settings.Designer.cs 75 | 76 | 77 | True 78 | Settings.settings 79 | True 80 | 81 | 82 | 83 | 84 | 85 | 86 | 93 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Contracts/IImage.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | 3 | namespace DesignPatterns.Proxy.Exemplo.Contracts 4 | { 5 | /// 6 | /// Contrat that defines the methods an image class has to implement. 7 | /// 8 | public interface IImage 9 | { 10 | /// 11 | /// Shows an image. 12 | /// 13 | Image GetImage(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Implementations/HighResolutionImage.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Proxy.Exemplo.Contracts; 2 | using System.Drawing; 3 | using System.Drawing.Drawing2D; 4 | using System.IO; 5 | 6 | namespace DesignPatterns.Proxy.Exemplo.Implementations 7 | { 8 | /// 9 | /// Represents a high resolution image. 10 | /// 11 | public class HighResolutionImage : IImage 12 | { 13 | /// 14 | /// Image to load. 15 | /// 16 | private Image _image; 17 | 18 | public HighResolutionImage(string caminhoImagem) 19 | { 20 | LoadImage(caminhoImagem); 21 | } 22 | 23 | /// 24 | /// Loads a high resolution image. 25 | /// 26 | /// Image path on disk. 27 | private void LoadImage(string imagePath) 28 | { 29 | using (Stream stream = new FileStream(imagePath, FileMode.Open)) 30 | { 31 | // Read all image bytes. 32 | var bytes = new byte[stream.Length + 1]; 33 | stream.Read(bytes, 0, bytes.Length); 34 | 35 | // Load a bitmap from image bytes. 36 | _image = (Bitmap)new ImageConverter().ConvertFrom(bytes); 37 | } 38 | 39 | // Creates a graphics object to define image's quality. 40 | Graphics imageGraphics = Graphics.FromImage(_image); 41 | imageGraphics.InterpolationMode = InterpolationMode.High; 42 | 43 | // Draws the high resolution image. 44 | imageGraphics.DrawImage(_image, 0, 0); 45 | imageGraphics.Dispose(); 46 | } 47 | 48 | /// 49 | /// Returns a loaded high resolution image. 50 | /// 51 | /// Loaded image. 52 | public Image GetImage() => _image; 53 | } 54 | } -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Implementations/ImageProxy.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Proxy.Exemplo.Contracts; 2 | using System.Drawing; 3 | 4 | namespace DesignPatterns.Proxy.Exemplo.Implementations 5 | { 6 | /// 7 | /// Proxy to high resolution image class. Manages the image loading to avoid unnecessary memory usage. 8 | /// 9 | public class ImageProxy : IImage 10 | { 11 | private string _imagePath; 12 | private HighResolutionImage _highResolutionImage; 13 | 14 | public ImageProxy(string imagePath) 15 | { 16 | _imagePath = imagePath; 17 | } 18 | 19 | /// 20 | /// This method loads and returns the high resolution image. 21 | /// 22 | /// Loaded image. 23 | public Image GetImage() 24 | { 25 | _highResolutionImage = new HighResolutionImage(_imagePath); 26 | return _highResolutionImage.GetImage(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Program.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Proxy.Exemplo; 2 | using System; 3 | using System.Windows.Forms; 4 | 5 | namespace CSharp.DesignPatterns.Proxy 6 | { 7 | static class Program 8 | { 9 | /// 10 | /// The main entry point for the application. 11 | /// 12 | [STAThread] 13 | static void Main() 14 | { 15 | Application.EnableVisualStyles(); 16 | Application.SetCompatibleTextRenderingDefault(false); 17 | Application.Run(new frmImage()); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.Proxy")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.Proxy")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("f8dae7a9-e27b-4198-b143-67e5d24b2753")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace CSharp.DesignPatterns.Proxy.Properties 12 | { 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources 26 | { 27 | 28 | private static global::System.Resources.ResourceManager resourceMan; 29 | 30 | private static global::System.Globalization.CultureInfo resourceCulture; 31 | 32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 33 | internal Resources() 34 | { 35 | } 36 | 37 | /// 38 | /// Returns the cached ResourceManager instance used by this class. 39 | /// 40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 41 | internal static global::System.Resources.ResourceManager ResourceManager 42 | { 43 | get 44 | { 45 | if ((resourceMan == null)) 46 | { 47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CSharp.DesignPatterns.Proxy.Properties.Resources", typeof(Resources).Assembly); 48 | resourceMan = temp; 49 | } 50 | return resourceMan; 51 | } 52 | } 53 | 54 | /// 55 | /// Overrides the current thread's CurrentUICulture property for all 56 | /// resource lookups using this strongly typed resource class. 57 | /// 58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 59 | internal static global::System.Globalization.CultureInfo Culture 60 | { 61 | get 62 | { 63 | return resourceCulture; 64 | } 65 | set 66 | { 67 | resourceCulture = value; 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace CSharp.DesignPatterns.Proxy.Properties 12 | { 13 | 14 | 15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] 17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 18 | { 19 | 20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 21 | 22 | public static Settings Default 23 | { 24 | get 25 | { 26 | return defaultInstance; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/frmImage.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Proxy.Exemplo 2 | { 3 | partial class frmImage 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | this.pcbImage = new System.Windows.Forms.PictureBox(); 32 | this.ofdSelect = new System.Windows.Forms.OpenFileDialog(); 33 | this.btnSelect = new System.Windows.Forms.Button(); 34 | this.btnLoad = new System.Windows.Forms.Button(); 35 | this.txtPath = new System.Windows.Forms.TextBox(); 36 | ((System.ComponentModel.ISupportInitialize)(this.pcbImage)).BeginInit(); 37 | this.SuspendLayout(); 38 | // 39 | // pcbImage 40 | // 41 | this.pcbImage.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; 42 | this.pcbImage.Location = new System.Drawing.Point(12, 12); 43 | this.pcbImage.Name = "pcbImage"; 44 | this.pcbImage.Size = new System.Drawing.Size(838, 389); 45 | this.pcbImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; 46 | this.pcbImage.TabIndex = 0; 47 | this.pcbImage.TabStop = false; 48 | // 49 | // btnSelect 50 | // 51 | this.btnSelect.Location = new System.Drawing.Point(12, 433); 52 | this.btnSelect.Name = "btnSelect"; 53 | this.btnSelect.Size = new System.Drawing.Size(838, 23); 54 | this.btnSelect.TabIndex = 1; 55 | this.btnSelect.Text = "Select Image"; 56 | this.btnSelect.UseVisualStyleBackColor = true; 57 | this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click); 58 | // 59 | // btnLoad 60 | // 61 | this.btnLoad.Location = new System.Drawing.Point(12, 462); 62 | this.btnLoad.Name = "btnLoad"; 63 | this.btnLoad.Size = new System.Drawing.Size(838, 23); 64 | this.btnLoad.TabIndex = 2; 65 | this.btnLoad.Text = "Load Image"; 66 | this.btnLoad.UseVisualStyleBackColor = true; 67 | this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); 68 | // 69 | // txtPath 70 | // 71 | this.txtPath.Location = new System.Drawing.Point(12, 407); 72 | this.txtPath.Name = "txtPath"; 73 | this.txtPath.ReadOnly = true; 74 | this.txtPath.Size = new System.Drawing.Size(838, 20); 75 | this.txtPath.TabIndex = 3; 76 | this.txtPath.Text = "Select an image..."; 77 | // 78 | // frmImage 79 | // 80 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 81 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 82 | this.ClientSize = new System.Drawing.Size(862, 497); 83 | this.Controls.Add(this.txtPath); 84 | this.Controls.Add(this.btnLoad); 85 | this.Controls.Add(this.btnSelect); 86 | this.Controls.Add(this.pcbImage); 87 | this.Name = "frmImage"; 88 | this.Text = "Image Proxy"; 89 | ((System.ComponentModel.ISupportInitialize)(this.pcbImage)).EndInit(); 90 | this.ResumeLayout(false); 91 | this.PerformLayout(); 92 | 93 | } 94 | 95 | #endregion 96 | 97 | private System.Windows.Forms.PictureBox pcbImage; 98 | private System.Windows.Forms.OpenFileDialog ofdSelect; 99 | private System.Windows.Forms.Button btnSelect; 100 | private System.Windows.Forms.Button btnLoad; 101 | private System.Windows.Forms.TextBox txtPath; 102 | } 103 | } 104 | 105 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/frmImage.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Proxy.Exemplo.Contracts; 2 | using DesignPatterns.Proxy.Exemplo.Implementations; 3 | using System; 4 | using System.Windows.Forms; 5 | 6 | namespace DesignPatterns.Proxy.Exemplo 7 | { 8 | /// 9 | /// Proxy pattern example. In this example, we have a container that shows an chosen imagem only when user 10 | /// clicks on button "Load Image". The image class renders a high resolution image, process that needs a lot 11 | /// of memory. To avoid unnecessary loading until the user clicks the button, a proxy class is created to the 12 | /// image class, allowing the image to be loaded only when "GetImage" method is called, and not during class 13 | /// creation. 14 | /// 15 | /// The goal of proxy pattern is to control codes where performance is something to consider. As other examples, 16 | /// the image loading could have been managed in a different way, but this approach was chosen to show how to 17 | /// apply the pattern. 18 | /// 19 | public partial class frmImage : Form 20 | { 21 | private IImage _selectedImage; 22 | 23 | public frmImage() 24 | { 25 | InitializeComponent(); 26 | } 27 | 28 | /// 29 | /// Select image button click event. 30 | /// 31 | /// 32 | /// 33 | private void btnSelect_Click(object sender, EventArgs e) 34 | { 35 | var dialogResult = ofdSelect.ShowDialog(); 36 | if (dialogResult == DialogResult.OK) 37 | { 38 | _selectedImage = new ImageProxy(ofdSelect.FileName); 39 | txtPath.Text = "Selected: " + ofdSelect.FileName; 40 | } 41 | } 42 | 43 | /// 44 | /// Loads a selected image to the display box. 45 | /// 46 | /// 47 | /// 48 | private void btnLoad_Click(object sender, EventArgs e) 49 | { 50 | if (_selectedImage == null) 51 | { 52 | MessageBox.Show("Select an image to load on box."); 53 | return; 54 | } 55 | pcbImage.Image = _selectedImage.GetImage(); 56 | pcbImage.Refresh(); 57 | txtPath.Text = "Loaded image"; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Proxy/frmImage.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 17, 17 122 | 123 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Singleton/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Singleton/CSharp.DesignPatterns.Singleton.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {3005CFBB-D0DA-4618-8BBE-300B9C2BBFA9} 8 | Exe 9 | Properties 10 | CSharp.DesignPatterns.Singleton 11 | CSharp.DesignPatterns.Singleton 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 64 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Singleton/Container/IoCContainer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace CSharp.DesignPatterns.Singleton.Container 5 | { 6 | /// 7 | /// Simple IoC container to show an example of Singleton pattern. 8 | /// 9 | public class IoCContainer 10 | { 11 | /// 12 | /// Container instance loaded only once on memory. 13 | /// 14 | private static IoCContainer _container; 15 | 16 | /// 17 | /// Dictionary that maps interface types to class types. 18 | /// 19 | private readonly IDictionary _types = new Dictionary(); 20 | 21 | /// 22 | /// To use singleton pattern, the class constructor must have to be private. 23 | /// 24 | private IoCContainer() { } 25 | 26 | /// 27 | /// The container is accessed using a get property which creates the container the first time it's called 28 | /// and then return this instance every time the property is accessed. 29 | /// 30 | public static IoCContainer Instance 31 | { 32 | get 33 | { 34 | if (_container == null) 35 | _container = new IoCContainer(); 36 | return _container; 37 | } 38 | } 39 | 40 | /// 41 | /// Map an interface type to a class type. 42 | /// 43 | /// Interface type. 44 | /// Implementation type. 45 | public void Register() 46 | { 47 | _types[typeof(TInterface)] = typeof(TImplementation); 48 | } 49 | 50 | /// 51 | /// Returns an instance of a correspondig type. 52 | /// 53 | /// Interface. 54 | public TInterface Get() 55 | { 56 | return (TInterface)Get(typeof(TInterface)); 57 | } 58 | 59 | /// 60 | /// Returns an instance of a correspondig type. 61 | /// 62 | /// Type we want to get the corresponding implementation. 63 | public object Get(Type type) 64 | { 65 | var constructor = _types[type].GetConstructors()[0]; 66 | var constructorParameters = constructor.GetParameters(); 67 | 68 | if (constructorParameters.Length == 0) 69 | return Activator.CreateInstance(_types[type]); 70 | 71 | object[] parameters = new object[constructorParameters.Length]; 72 | 73 | for (int index = 0; index < constructorParameters.Length; index++) 74 | { 75 | parameters[index] = Get(constructorParameters[index].ParameterType); 76 | } 77 | 78 | return constructor.Invoke(parameters); 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Singleton/Contracts/IToDoRepository.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Singleton.Contracts 2 | { 3 | /// 4 | /// Contract to define the methods of a given repository. 5 | /// 6 | public interface IToDoRepository 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Singleton/Program.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Singleton.Container; 2 | using CSharp.DesignPatterns.Singleton.Contracts; 3 | using CSharp.DesignPatterns.Singleton.Repositories; 4 | using System; 5 | 6 | namespace CSharp.DesignPatterns.Singleton 7 | { 8 | class Program 9 | { 10 | /// 11 | /// Singleton pattern example. In this example, we have a simple inversion of control container created for mapping 12 | /// interfaces to its implementations. As we want the container to be configured only once when the application 13 | /// starts, we implement the singleton pattern to assert only one instance will be created and the mapping process 14 | /// will be done just at creation time. This is achieved making the container's constructor private and creating 15 | /// a get property that will check wheter the cotainer was created before. If the instance wasn't created yet, 16 | /// the property creates the instance and asserts every time it's accessed the created instance will be used. 17 | /// 18 | /// Note: in a real world application, it isn't recommended to use a so simple container, because it doesn't handle 19 | /// object creation when interfaces are not mapped and because scopes aren't configured. Not necessarily a container 20 | /// will use singleton, I made this one this way just to show an example of pattern. 21 | /// 22 | static void Main(string[] args) 23 | { 24 | // The container is accessed every time using the get property. 25 | IoCContainer.Instance.Register(); 26 | //IoCContainer.Instance.Register(); 27 | 28 | var repository = IoCContainer.Instance.Get(); 29 | 30 | Console.WriteLine($"Mapped type: {repository.GetType().ToString()}"); 31 | Console.ReadKey(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Singleton/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.Singleton")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.Singleton")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("3005cfbb-d0da-4618-8bbe-300b9c2bbfa9")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Singleton/Repositories/ToDoRepositoryADO.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Singleton.Contracts; 2 | 3 | namespace CSharp.DesignPatterns.Singleton.Repositories 4 | { 5 | /// 6 | /// Fictional implementation of repository that uses ADO.NET for data access. 7 | /// 8 | public class ToDoRepositoryADO : IToDoRepository 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Singleton/Repositories/ToDoRepositoryEntity.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Singleton.Contracts; 2 | 3 | namespace CSharp.DesignPatterns.Singleton.Repositories 4 | { 5 | /// 6 | /// Fictional implementation of a repository that uses Entity Framework for data access. 7 | /// 8 | public class ToDoRepositoryEntity : IToDoRepository 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/CSharp.DesignPatterns.Strategy.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {66DE8197-599B-43CC-9E5E-5B1C88D36E86} 8 | Exe 9 | Properties 10 | CSharp.DesignPatterns.Strategy 11 | CSharp.DesignPatterns.Strategy 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 69 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/Contracts/IBasketDiscountStrategy.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Strategy.Domain; 2 | using System.Collections.Generic; 3 | 4 | namespace CSharp.DesignPatterns.Strategy.Contracts 5 | { 6 | /// 7 | /// Defines a discount strategy to be applied over a products list. 8 | /// 9 | public interface IBasketDiscountStrategy 10 | { 11 | /// 12 | /// Calculates the total price for all products in a list. 13 | /// 14 | /// Products. 15 | /// Total price. 16 | decimal TotalPriceFor(IList products); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/DiscountStrategies/NoDiscountStrategy.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Strategy.Contracts; 2 | using CSharp.DesignPatterns.Strategy.Domain; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace CSharp.DesignPatterns.Strategy.DiscountStrategies 7 | { 8 | /// 9 | /// Discount strategy for a products list where we musn't apply a discount value. 10 | /// 11 | public class NoDiscountStrategy : IBasketDiscountStrategy 12 | { 13 | /// 14 | /// Calculates the total price for all products in a list. 15 | /// 16 | /// Products. 17 | /// Total price. 18 | public decimal TotalPriceFor(IList products) 19 | { 20 | decimal price = 0; 21 | 22 | products.AsParallel().ForAll(p => 23 | { 24 | price += p.Price; 25 | }); 26 | 27 | return price; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/DiscountStrategies/PerItemPercentualDiscountStrategy.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Strategy.Contracts; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using CSharp.DesignPatterns.Strategy.Domain; 5 | 6 | namespace CSharp.DesignPatterns.Strategy.DiscountStrategies 7 | { 8 | /// 9 | /// Discount strategy for a products list where we must apply a percentage discount over each product, and them sum the total price. 10 | /// 11 | public class PerItemPercentualDiscountStrategy : IBasketDiscountStrategy 12 | { 13 | /// 14 | /// In this example, the percentage is fixed in 2%. 15 | /// 16 | private const int discountPercent = 2; 17 | 18 | /// 19 | /// Calculates the total price for all products in a list. 20 | /// 21 | /// Products. 22 | /// Total price. 23 | public decimal TotalPriceFor(IList products) 24 | { 25 | decimal price = 0; 26 | 27 | products.AsParallel().ForAll(p => 28 | { 29 | if (p.Price > 0) 30 | { 31 | var productPrice = p.Price - (p.Price * discountPercent) / 100; 32 | price += productPrice; 33 | } 34 | }); 35 | 36 | return price; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/DiscountStrategies/PercentageDiscountStrategy.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Strategy.Contracts; 2 | using CSharp.DesignPatterns.Strategy.Domain; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace CSharp.DesignPatterns.Strategy.DiscountStrategies 7 | { 8 | /// 9 | /// Discount strategy for a products list that we must apply a percentage discount over the total price. 10 | /// 11 | public class PercentageDiscountStrategy : IBasketDiscountStrategy 12 | { 13 | /// 14 | /// In this example, the percentage is fixed in 15%. 15 | /// 16 | private const int discountPercent = 15; 17 | 18 | /// 19 | /// Calculates the total price for all products in a list. 20 | /// 21 | /// Products. 22 | /// Total price. 23 | public decimal TotalPriceFor(IList products) 24 | { 25 | decimal price = 0; 26 | 27 | products.AsParallel().ForAll(p => 28 | { 29 | price += p.Price; 30 | }); 31 | 32 | if (price > 0) 33 | price -= (price * discountPercent) / 100; 34 | 35 | return price; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/Domain/Basket.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Strategy.Contracts; 2 | using CSharp.DesignPatterns.Strategy.Factories; 3 | using System.Collections.Generic; 4 | 5 | namespace CSharp.DesignPatterns.Strategy.Domain 6 | { 7 | /// 8 | /// Represents an ecommerce application basket. 9 | /// 10 | public class Basket 11 | { 12 | /// 13 | /// Producst lists that will be bought. 14 | /// 15 | private IList _products; 16 | 17 | /// 18 | /// Discount strategy used to determine the total price of all products according to a discount type. 19 | /// 20 | private IBasketDiscountStrategy _discountStrategy; 21 | 22 | public Basket(EDiscountType discountType) 23 | { 24 | _products = new List(); 25 | 26 | // Here the discount strategy is defined, according to a desired kind of discount type. 27 | _discountStrategy = DiscountStrategyFactory.DiscountStrategyFor(discountType); 28 | } 29 | 30 | /// 31 | /// Defines a discount type to be applied over all products of basket. 32 | /// 33 | /// Discount type which will be applied over the products list. 34 | public void SetDiscountType(EDiscountType discountType) 35 | { 36 | _discountStrategy = DiscountStrategyFactory.DiscountStrategyFor(discountType); 37 | } 38 | 39 | /// 40 | /// Add a product to basket. 41 | /// 42 | /// Product to be added. 43 | public void AddProduct(Product produto) 44 | { 45 | _products.Add(produto); 46 | } 47 | 48 | /// 49 | /// Calculates the total price of all items on basket. 50 | /// 51 | /// Total price. 52 | public decimal TotalPrice() => _discountStrategy.TotalPriceFor(_products); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/Domain/EDiscountType.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Strategy.Domain 2 | { 3 | /// 4 | /// Discount types to apply over products. 5 | /// 6 | public enum EDiscountType : byte 7 | { 8 | NoDiscount = 0, 9 | PercentageDiscount = 1, 10 | PerItemPercentageDiscount = 2 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/Domain/Product.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.Strategy.Domain 2 | { 3 | /// 4 | /// Product to sell. 5 | /// 6 | public class Product 7 | { 8 | /// 9 | /// Product's price. 10 | /// 11 | public decimal Price { get; private set; } 12 | 13 | /// 14 | /// Product's name. 15 | /// 16 | public string Name { get; private set; } 17 | 18 | public Product(string name, decimal value) 19 | { 20 | Name = name; 21 | Price = value; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/Factories/DiscountStrategyFactory.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Strategy.Contracts; 2 | using CSharp.DesignPatterns.Strategy.DiscountStrategies; 3 | using CSharp.DesignPatterns.Strategy.Domain; 4 | using System; 5 | 6 | namespace CSharp.DesignPatterns.Strategy.Factories 7 | { 8 | /// 9 | /// Factory that creates discount strategies accourding to a desired discount type. 10 | /// 11 | public static class DiscountStrategyFactory 12 | { 13 | /// 14 | /// Returns a discount strategy acourding to a discount type. 15 | /// 16 | /// Discount type to be applied. 17 | /// Discount strategy. 18 | public static IBasketDiscountStrategy DiscountStrategyFor(EDiscountType discountType) 19 | { 20 | switch (discountType) 21 | { 22 | case EDiscountType.NoDiscount: 23 | return new NoDiscountStrategy(); 24 | case EDiscountType.PercentageDiscount: 25 | return new PercentageDiscountStrategy(); 26 | case EDiscountType.PerItemPercentageDiscount: 27 | return new PerItemPercentualDiscountStrategy(); 28 | default: 29 | throw new ArgumentException("There is no discount strategy defined to the specified discount type."); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/Program.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.Strategy.Domain; 2 | using System; 3 | 4 | namespace CSharp.DesignPatterns.Strategy 5 | { 6 | class Program 7 | { 8 | /// 9 | /// Strategy pattern example. In this exaple, we have a basket of a common ecommerce application, which contains a products list 10 | /// with different prices. The prices must be used to calculate the total price, but in three different situations: 11 | /// - The total price can be the sum of all products; 12 | /// - The total price can be the sum of all products, with a percentage discount of 15%; 13 | /// - The total price can be the sum of all products, with a percentage discount of 2% over each product. 14 | /// 15 | /// There is an enum used to determine de discount strategy to be applied over the producs lists on the basket. The definition 16 | /// of the desired strategy is responsability of the basket, that internally uses a factory that creates the strategy. A discount 17 | /// strategy interface assures all strategys have a method to calculate the total price for that situation, and the process is 18 | /// completely transparent because the only thing needed to pass to the basket, in addition to the products, is the desired 19 | /// discount type. 20 | /// 21 | /// The advantage of this approach is that if you need to implement a new discount strategy (example: black friday discount 22 | /// strategy), you will only need to create a new implementation for the strategy interface, and change the factory and the 23 | /// enumerator to contemplate the changes. 24 | /// 25 | /// 26 | static void Main(string[] args) 27 | { 28 | var soda = new Product("Soda", 5); 29 | var pizza = new Product("Pizza", 30); 30 | var pizza2 = new Product("Second Pizza", 35); 31 | 32 | var basket = new Basket(EDiscountType.NoDiscount); 33 | basket.AddProduct(soda); 34 | basket.AddProduct(pizza); 35 | basket.AddProduct(pizza2); 36 | 37 | Console.WriteLine("Total price with no discount: $ " + basket.TotalPrice()); 38 | 39 | basket.SetDiscountType(EDiscountType.PercentageDiscount); 40 | Console.WriteLine("Total price with a percentage discount of 15%, applied over the total price: $ " + basket.TotalPrice()); 41 | 42 | basket.SetDiscountType(EDiscountType.PerItemPercentageDiscount); 43 | Console.WriteLine("Total price with a percentage discount of 2%, applied over the price of each product $ " + basket.TotalPrice()); 44 | 45 | Console.ReadKey(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.Strategy/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.Strategy")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.Strategy")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("66de8197-599b-43cc-9e5e-5b1c88d36e86")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 |
5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/CSharp.DesignPatterns.TemplateMethod.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {4785CE84-7281-4613-8CCD-BA8B79FA4902} 8 | Library 9 | Properties 10 | CSharp.DesignPatterns.TemplateMethod 11 | CSharp.DesignPatterns.TemplateMethod 12 | v4.6.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 35 | True 36 | 37 | 38 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 39 | True 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 201707051924134_Test.cs 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 201707051924134_Test.cs 70 | 71 | 72 | 73 | 80 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Context/ExampleDbContext.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.TemplateMethod.Mapping; 2 | using CSharp.DesignPatterns.TemplateMethod.Model; 3 | using System.Data.Entity; 4 | 5 | namespace CSharp.DesignPatterns.TemplateMethod.Context 6 | { 7 | /// 8 | /// Template method pattern example. In this example, we have an application where we need to map model 9 | /// entities to database tables, because we want to use code first approach to develop the database. 10 | /// We have an user class and we need to define that a user has two properties: 11 | /// - Id, which will identify the user. It needs to be an identity column; 12 | /// - Name, which will be required and will have a maxlength of 50 characters. 13 | /// 14 | /// To map these classes, a mapping base class was created, and a template method is called at runtime 15 | /// when the mapping class is created. This template method calls all other mapping methods of each derived 16 | /// class in order to map a model class to a database table. 17 | /// 18 | /// The goal of template method is to control code flow when we need to call specific methods in sequence, but 19 | /// we want to distinguish these methods for each derived class. 20 | /// 21 | public class ExampleDbContext : DbContext 22 | { 23 | /// 24 | /// Users set. 25 | /// 26 | public DbSet User { get; set; } 27 | 28 | /// 29 | /// Overrides the default constructor to set the connection string. 30 | /// 31 | public ExampleDbContext() : base("name=ExampleDbContext") { } 32 | 33 | /// 34 | /// Overrides this method to add mappings. 35 | /// 36 | /// Model builder. 37 | protected override void OnModelCreating(DbModelBuilder modelBuilder) 38 | { 39 | // Adds user mapping. When you run a migration, the User class will be mapped as specified on 40 | // UserMapping class, and any other mapping class specified here will be considered for new migrations. 41 | modelBuilder.Configurations.Add(new UserMapping()); 42 | base.OnModelCreating(modelBuilder); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Mapping/Base/MappingTemplate.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Entity.ModelConfiguration; 2 | 3 | namespace CSharp.DesignPatterns.TemplateMethod.Mapping.Base 4 | { 5 | /// 6 | /// Mapping template. A inherited class has to implement all abstract methods to set how a determined class 7 | /// will be mapped to database. 8 | /// 9 | /// 10 | public abstract class MappingTemplate : EntityTypeConfiguration where T : class 11 | { 12 | /// 13 | /// Calls the template method to execute mapping. 14 | /// 15 | public MappingTemplate() 16 | { 17 | MapTemplateMethod(); 18 | } 19 | 20 | /// 21 | /// Template method that defines the sequence of methods called to configure an entity mapping. 22 | /// 23 | public void MapTemplateMethod() 24 | { 25 | CreateTable(); 26 | CreateColumns(); 27 | SetPrimaryKey(); 28 | SetForeignKeys(); 29 | } 30 | 31 | /// 32 | /// Creates the corresponding table. 33 | /// 34 | protected abstract void CreateTable(); 35 | 36 | /// 37 | /// Creates all table columns. 38 | /// 39 | protected abstract void CreateColumns(); 40 | 41 | /// 42 | /// Sets the primary key. 43 | /// 44 | protected abstract void SetPrimaryKey(); 45 | 46 | /// 47 | /// Sets the foreign keys. 48 | /// 49 | protected abstract void SetForeignKeys(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Mapping/UserMapping.cs: -------------------------------------------------------------------------------- 1 | using CSharp.DesignPatterns.TemplateMethod.Mapping.Base; 2 | using CSharp.DesignPatterns.TemplateMethod.Model; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | 5 | namespace CSharp.DesignPatterns.TemplateMethod.Mapping 6 | { 7 | /// 8 | /// Maps the users table. 9 | /// 10 | public class UserMapping : MappingTemplate 11 | { 12 | 13 | /// 14 | /// Creates the corresponding table. 15 | /// 16 | protected override void CreateTable() 17 | { 18 | ToTable("Users"); 19 | } 20 | 21 | /// 22 | /// Creates all table columns. 23 | /// 24 | protected override void CreateColumns() 25 | { 26 | Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 27 | Property(p => p.Name).IsRequired().HasMaxLength(50); 28 | } 29 | 30 | /// 31 | /// Sets the primary key. 32 | /// 33 | protected override void SetPrimaryKey() 34 | { 35 | HasKey(p => p.Id); 36 | } 37 | 38 | /// 39 | /// Sets the foreign keys. 40 | /// 41 | protected override void SetForeignKeys() 42 | { 43 | // Empty, there aren't foreign keys. 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Migrations/201707051924134_Test.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | namespace CSharp.DesignPatterns.TemplateMethod.Migrations 3 | { 4 | using System.CodeDom.Compiler; 5 | using System.Data.Entity.Migrations; 6 | using System.Data.Entity.Migrations.Infrastructure; 7 | using System.Resources; 8 | 9 | [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] 10 | public sealed partial class Test : IMigrationMetadata 11 | { 12 | private readonly ResourceManager Resources = new ResourceManager(typeof(Test)); 13 | 14 | string IMigrationMetadata.Id 15 | { 16 | get { return "201707051924134_Test"; } 17 | } 18 | 19 | string IMigrationMetadata.Source 20 | { 21 | get { return null; } 22 | } 23 | 24 | string IMigrationMetadata.Target 25 | { 26 | get { return Resources.GetString("Target"); } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Migrations/201707051924134_Test.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.TemplateMethod.Migrations 2 | { 3 | using System; 4 | using System.Data.Entity.Migrations; 5 | 6 | public partial class Test : DbMigration 7 | { 8 | public override void Up() 9 | { 10 | CreateTable( 11 | "dbo.Users", 12 | c => new 13 | { 14 | Id = c.Long(nullable: false, identity: true), 15 | Name = c.String(nullable: false, maxLength: 50), 16 | }) 17 | .PrimaryKey(t => t.Id); 18 | 19 | } 20 | 21 | public override void Down() 22 | { 23 | DropTable("dbo.Users"); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Migrations/201707051924134_Test.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | H4sIAAAAAAAEAM1X227bRhB9L9B/IPbZ4dpJW6QGmcCV7MJoZBuhk/cVOaIW3Qu7uzSkb+tDP6m/0FneRUqK7AZBYECwlnM5c/bMDPXv3/9E7zdSBE9gLNcqJhfhOQlApTrjKo9J6Vav3pL37378IbrO5Cb43Nq98XboqWxM1s4Vl5TadA2S2VDy1GirVy5MtaQs0/T1+fmv9OKCAoYgGCsIoo+lclxC9QW/zrRKoXAlEwudgbDNOT5JqqjBHZNgC5ZCTGbJmpkinIPluXpgzoFRNnwEWQjmYAFurbMQAzrYOBJcCc4QYwJiRQKmlHbMYQWXnywkzmiVJwUeMPG4LQDtVkxYaCq77M1PLfL8tS+S9o5tqLS0TstnBrx407BGx+4v4p50rCKv18i/2/qqK25jgoQYEowTXc6E8UYn0l7dXuhDnQWnOJx1ikLh+T90K4UrDcQKSmeYOAseyqXg6R+wfdR/gopVKcSwEqwFn+0c4NGD0QUYt/0Iq6a+24wEdNePjh07t4FPXf2tcr/8RII7TM6WAjqhDJhKnDbwOygwWF7WFOxjQEX1JPsol/9ss6Eysf1IsGCbD6Byt47Jz9hvN3wDWXvQAPikODYr+jhTwh6Aw6QR7W99qgXfMowj/AbQ9YbhVcF82fXSRBx40Y0+bANgt8Q6cAJuR2M9iLovw/p4H9IOUz8QaD0R2slBD4yOaMGKAkkcjJLmJEiaOfIqeX4byToGTe2eburQdplQEiyH0VNMjUhvuLFuzhxbMn9Ps0xOzCY3cIDdNt2A5HE/9Jy3xv7/2uE5AzXcF73n9gbLlaj3qnLoAO4HVTkmKRPM7Om7mRalVId695h33UlD//pkGiGiI9xj2uiEt9EEGd/BMQ2PTbrsnZZHmo0a/ZywE8eCqk1IgNQ88cyLKdlaBzL0BmHyl5gJjvX2Bgum+Aqsq4csQb2/HS3P72eRUWszccI2++ZbYslz7kn94io4OqaP7wb1xEyKDTvZDl9x9E/n0/+Y67UUY5ItNdZQI/RP7ItH/rQtIjp8oYzqUdaF8K+XClKvtz5oa3OrVrqlGysaImpNRreBE5FlSMyVcXzFUoePU7C22tifmSj97pRLyG7VfemK0l1ZC3Ipdt4AIno8f7XXdjFH94X/Zr9GCQiTYwlwr34rucg63Dd7lHMghNdII3FEhW8sGC7fdpHutDoxUEPfHApQvkHaxWPvVcKe4CXYUF4fIGfptp1uh4N8+SJ2aY/mnOWGSdvE6P39jyTqfyW9+w/C+LhBVw0AAA== 122 | 123 | 124 | dbo 125 | 126 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Migrations/Configuration.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.TemplateMethod.Migrations 2 | { 3 | using System; 4 | using System.Data.Entity; 5 | using System.Data.Entity.Migrations; 6 | using System.Linq; 7 | 8 | internal sealed class Configuration : DbMigrationsConfiguration 9 | { 10 | public Configuration() 11 | { 12 | AutomaticMigrationsEnabled = false; 13 | } 14 | 15 | protected override void Seed(CSharp.DesignPatterns.TemplateMethod.Context.ExampleDbContext context) 16 | { 17 | // This method will be called after migrating to the latest version. 18 | 19 | // You can use the DbSet.AddOrUpdate() helper extension method 20 | // to avoid creating duplicate seed data. E.g. 21 | // 22 | // context.People.AddOrUpdate( 23 | // p => p.FullName, 24 | // new Person { FullName = "Andrew Peters" }, 25 | // new Person { FullName = "Brice Lambson" }, 26 | // new Person { FullName = "Rowan Miller" } 27 | // ); 28 | // 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Model/User.cs: -------------------------------------------------------------------------------- 1 | namespace CSharp.DesignPatterns.TemplateMethod.Model 2 | { 3 | /// 4 | /// Represents an user. 5 | /// 6 | public class User 7 | { 8 | /// 9 | /// User identifier. 10 | /// 11 | public long Id { get; set; } 12 | 13 | /// 14 | /// User's name 15 | /// 16 | public string Name { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CSharp.DesignPatterns.TemplateMethod")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CSharp.DesignPatterns.TemplateMethod")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("4785ce84-7281-4613-8ccd-ba8b79fa4902")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.TemplateMethod/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /CSharp.DesignPatterns.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Behaviorals", "Behaviorals", "{7F7008E6-0041-47DA-9FC5-800F51D6D1BD}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Creationals", "Creationals", "{6A8855D0-5572-4CF6-8F42-7A333DE4190A}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Structurals", "Structurals", "{284D04AD-E6D6-4FE0-9C3D-1943D4BBD24D}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.Observer", "CSharp.DesignPatterns.Observer\CSharp.DesignPatterns.Observer.csproj", "{BAB7507E-5F86-4EF0-A295-5E389DDE5224}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.Strategy", "CSharp.DesignPatterns.Strategy\CSharp.DesignPatterns.Strategy.csproj", "{66DE8197-599B-43CC-9E5E-5B1C88D36E86}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.AbstractFactory", "CSharp.DesignPatterns.AbstractFactory\CSharp.DesignPatterns.AbstractFactory.csproj", "{C161C76B-3E4B-4D68-A598-32966813B3A1}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.Builder", "CSharp.DesignPatterns.Builder\CSharp.DesignPatterns.Builder.csproj", "{AD6032EA-35B4-4AFF-B555-8C8934CE88E8}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.Singleton", "CSharp.DesignPatterns.Singleton\CSharp.DesignPatterns.Singleton.csproj", "{3005CFBB-D0DA-4618-8BBE-300B9C2BBFA9}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.Adapter", "CSharp.DesignPatterns.Adapter\CSharp.DesignPatterns.Adapter.csproj", "{34E21A8D-E0F0-4189-89D1-F635E19963CD}" 23 | EndProject 24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.Composite", "CSharp.DesignPatterns.Composite\CSharp.DesignPatterns.Composite.csproj", "{28E77374-99A3-4787-AE36-F1552A47F3E6}" 25 | EndProject 26 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.Decorator", "CSharp.DesignPatterns.Decorator\CSharp.DesignPatterns.Decorator.csproj", "{137264F8-34E7-4512-B309-1CED265504C3}" 27 | EndProject 28 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.Proxy", "CSharp.DesignPatterns.Proxy\CSharp.DesignPatterns.Proxy.csproj", "{F8DAE7A9-E27B-4198-B143-67E5D24B2753}" 29 | EndProject 30 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp.DesignPatterns.TemplateMethod", "CSharp.DesignPatterns.TemplateMethod\CSharp.DesignPatterns.TemplateMethod.csproj", "{4785CE84-7281-4613-8CCD-BA8B79FA4902}" 31 | EndProject 32 | Global 33 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 34 | Debug|Any CPU = Debug|Any CPU 35 | Release|Any CPU = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 38 | {BAB7507E-5F86-4EF0-A295-5E389DDE5224}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {BAB7507E-5F86-4EF0-A295-5E389DDE5224}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {BAB7507E-5F86-4EF0-A295-5E389DDE5224}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {BAB7507E-5F86-4EF0-A295-5E389DDE5224}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {66DE8197-599B-43CC-9E5E-5B1C88D36E86}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {66DE8197-599B-43CC-9E5E-5B1C88D36E86}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {66DE8197-599B-43CC-9E5E-5B1C88D36E86}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {66DE8197-599B-43CC-9E5E-5B1C88D36E86}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {C161C76B-3E4B-4D68-A598-32966813B3A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {C161C76B-3E4B-4D68-A598-32966813B3A1}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {C161C76B-3E4B-4D68-A598-32966813B3A1}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {C161C76B-3E4B-4D68-A598-32966813B3A1}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {AD6032EA-35B4-4AFF-B555-8C8934CE88E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {AD6032EA-35B4-4AFF-B555-8C8934CE88E8}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {AD6032EA-35B4-4AFF-B555-8C8934CE88E8}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {AD6032EA-35B4-4AFF-B555-8C8934CE88E8}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {3005CFBB-D0DA-4618-8BBE-300B9C2BBFA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {3005CFBB-D0DA-4618-8BBE-300B9C2BBFA9}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {3005CFBB-D0DA-4618-8BBE-300B9C2BBFA9}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {3005CFBB-D0DA-4618-8BBE-300B9C2BBFA9}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {34E21A8D-E0F0-4189-89D1-F635E19963CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {34E21A8D-E0F0-4189-89D1-F635E19963CD}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {34E21A8D-E0F0-4189-89D1-F635E19963CD}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {34E21A8D-E0F0-4189-89D1-F635E19963CD}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {28E77374-99A3-4787-AE36-F1552A47F3E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 63 | {28E77374-99A3-4787-AE36-F1552A47F3E6}.Debug|Any CPU.Build.0 = Debug|Any CPU 64 | {28E77374-99A3-4787-AE36-F1552A47F3E6}.Release|Any CPU.ActiveCfg = Release|Any CPU 65 | {28E77374-99A3-4787-AE36-F1552A47F3E6}.Release|Any CPU.Build.0 = Release|Any CPU 66 | {137264F8-34E7-4512-B309-1CED265504C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 67 | {137264F8-34E7-4512-B309-1CED265504C3}.Debug|Any CPU.Build.0 = Debug|Any CPU 68 | {137264F8-34E7-4512-B309-1CED265504C3}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {137264F8-34E7-4512-B309-1CED265504C3}.Release|Any CPU.Build.0 = Release|Any CPU 70 | {F8DAE7A9-E27B-4198-B143-67E5D24B2753}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 71 | {F8DAE7A9-E27B-4198-B143-67E5D24B2753}.Debug|Any CPU.Build.0 = Debug|Any CPU 72 | {F8DAE7A9-E27B-4198-B143-67E5D24B2753}.Release|Any CPU.ActiveCfg = Release|Any CPU 73 | {F8DAE7A9-E27B-4198-B143-67E5D24B2753}.Release|Any CPU.Build.0 = Release|Any CPU 74 | {4785CE84-7281-4613-8CCD-BA8B79FA4902}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 75 | {4785CE84-7281-4613-8CCD-BA8B79FA4902}.Debug|Any CPU.Build.0 = Debug|Any CPU 76 | {4785CE84-7281-4613-8CCD-BA8B79FA4902}.Release|Any CPU.ActiveCfg = Release|Any CPU 77 | {4785CE84-7281-4613-8CCD-BA8B79FA4902}.Release|Any CPU.Build.0 = Release|Any CPU 78 | EndGlobalSection 79 | GlobalSection(SolutionProperties) = preSolution 80 | HideSolutionNode = FALSE 81 | EndGlobalSection 82 | GlobalSection(NestedProjects) = preSolution 83 | {BAB7507E-5F86-4EF0-A295-5E389DDE5224} = {7F7008E6-0041-47DA-9FC5-800F51D6D1BD} 84 | {66DE8197-599B-43CC-9E5E-5B1C88D36E86} = {7F7008E6-0041-47DA-9FC5-800F51D6D1BD} 85 | {C161C76B-3E4B-4D68-A598-32966813B3A1} = {6A8855D0-5572-4CF6-8F42-7A333DE4190A} 86 | {AD6032EA-35B4-4AFF-B555-8C8934CE88E8} = {6A8855D0-5572-4CF6-8F42-7A333DE4190A} 87 | {3005CFBB-D0DA-4618-8BBE-300B9C2BBFA9} = {6A8855D0-5572-4CF6-8F42-7A333DE4190A} 88 | {34E21A8D-E0F0-4189-89D1-F635E19963CD} = {284D04AD-E6D6-4FE0-9C3D-1943D4BBD24D} 89 | {28E77374-99A3-4787-AE36-F1552A47F3E6} = {284D04AD-E6D6-4FE0-9C3D-1943D4BBD24D} 90 | {137264F8-34E7-4512-B309-1CED265504C3} = {284D04AD-E6D6-4FE0-9C3D-1943D4BBD24D} 91 | {F8DAE7A9-E27B-4198-B143-67E5D24B2753} = {284D04AD-E6D6-4FE0-9C3D-1943D4BBD24D} 92 | {4785CE84-7281-4613-8CCD-BA8B79FA4902} = {7F7008E6-0041-47DA-9FC5-800F51D6D1BD} 93 | EndGlobalSection 94 | EndGlobal 95 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Evandro Gayer Gomes 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C# Design Patterns 2 | 3 | Design patterns examples applied in real world situations. The intent of this repository is to show how .NET developers can write clean code, easy to maintain, using consolidate patterns to approach software development common situations. 4 | 5 | Currently, there are 10 patterns implemented, divided by category in separeted projects: 6 | 7 | - Behavioral 8 | - Observer 9 | - Strategy 10 | - Template Method 11 | - Creational 12 | - Abstract Factory 13 | - Builder 14 | - Singleton 15 | - Structural 16 | - Adapter 17 | - Composite 18 | - Decorator 19 | - Proxy 20 | 21 | Feel free to study, use and modify the examples as you want. If you want to contribute adding new patterns to these examples or changing existing ones, clone the repository and start coding. 22 | 23 | Make development easier, make code cleaner! --------------------------------------------------------------------------------