├── .gitignore ├── DesignPatterns.Tests ├── AdapterTest.cs ├── BridgeTest.cs ├── BuilderTest.cs ├── DecoratorTest.cs ├── DesignPatterns.Tests.csproj ├── FactoryTest.cs ├── SingletonTest.cs ├── StrategyTest.cs └── TemplateMethodTest.cs ├── DesignPatterns.sln ├── DesignPatterns ├── Behavorial │ ├── Bridge │ │ ├── IConsole.cs │ │ ├── JoystickAdvanced.cs │ │ ├── JoystickBasic.cs │ │ ├── PlayStation.cs │ │ └── XBox.cs │ ├── Decorator │ │ ├── Componet │ │ │ └── Notifier.cs │ │ ├── Decorator │ │ │ ├── BaseDecorator.cs │ │ │ ├── FacebookDecorator.cs │ │ │ └── SlackDecorator.cs │ │ └── Interface │ │ │ └── INotifier.cs │ ├── Strategy │ │ ├── Commission.cs │ │ ├── Employee.cs │ │ ├── ICommission.cs │ │ └── Order.cs │ └── TemplateMethod │ │ ├── GitHubAuth.cs │ │ ├── GoogleAuth.cs │ │ ├── Login.cs │ │ └── User.cs ├── Creatinal │ ├── Builder │ │ ├── Director.cs │ │ ├── Vehicle.cs │ │ └── VehicleBuilder.cs │ ├── Factory │ │ ├── Driver.cs │ │ ├── Person.cs │ │ ├── PersonFactory.cs │ │ └── Pilot.cs │ └── Singleton │ │ └── Singleton.cs ├── DesignPatterns.csproj └── Structure │ └── Adapter │ ├── AdapterLogger.cs │ ├── CustomLogger.cs │ ├── ICustomLogger.cs │ ├── ILogger.cs │ ├── Logger.cs │ └── Service.cs └── 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 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /DesignPatterns.Tests/AdapterTest.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Structure.Adapter; 2 | using Xunit; 3 | 4 | namespace DesignPatterns.Tests 5 | { 6 | public class AdapterTest 7 | { 8 | [Fact] 9 | public void ShouldUseTwoDifferLogs() 10 | { 11 | var service = new Service(new Logger()); 12 | service.ToString(); 13 | service = new Service(new AdapterLogger(new CustomLogger())); 14 | service.ToString(); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /DesignPatterns.Tests/BridgeTest.cs: -------------------------------------------------------------------------------- 1 |  2 | using DesignPatterns.Behavorial.Bridge; 3 | using Xunit; 4 | 5 | namespace DesignPatterns.Tests 6 | { 7 | public class BridgeTest 8 | { 9 | [Fact] 10 | public void ShouldConectOnConsole() 11 | { 12 | var xBox = new XBox(); 13 | var remote = new JoystickBasic(xBox); 14 | xBox.Startup(); 15 | 16 | Assert.True(remote.ConectOnConsole()); 17 | } 18 | 19 | [Fact] 20 | public void ShouldShutdownConsole() 21 | { 22 | var playStation = new PlayStation(); 23 | var remote = new JoystickAdvanced(playStation); 24 | playStation.Startup(); 25 | 26 | Assert.True(remote.ConectOnConsole()); 27 | Assert.True(remote.ShutdownConsole()); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /DesignPatterns.Tests/BuilderTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using DesignPatterns.Creatinal.Builder; 3 | using Xunit; 4 | 5 | namespace DesignPatterns.Tests 6 | { 7 | public class BuilderTest 8 | { 9 | [Fact] 10 | public void ShouldGetCar() 11 | { 12 | var director = new Director(new CarBuilder("", DateTime.Now, 123.1m)); 13 | var car = director.VehicleBuilder.GetVehicle(); 14 | 15 | Assert.Equal(VehicleType.Automobile, car.VehicleType); 16 | } 17 | 18 | [Fact] 19 | public void ShouldGetMotocycle() 20 | { 21 | var director = new Director(new MotocycleBuilder("", DateTime.Now, 123.2m)); 22 | var motocycle = director.VehicleBuilder.GetVehicle(); 23 | 24 | Assert.Equal(VehicleType.Motocycle, motocycle.VehicleType); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /DesignPatterns.Tests/DecoratorTest.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Behavorial.Decorator; 2 | using DesignPatterns.Decorator; 3 | using DesignPatterns.Decorator.Componet; 4 | using Xunit; 5 | 6 | namespace DesignPatterns.Tests 7 | { 8 | public class DecoratorTest 9 | { 10 | [Fact] 11 | public void ShouldGetMDecoratedMessages() 12 | { 13 | var decorator = new BaseDecorator(new Notifier("O Sistema falhou!")); 14 | var decorator2 = new SlackDecorator(decorator); 15 | var decorator3 = new FacebookDecorator(decorator2); 16 | 17 | var messageOne = "O Sistema falhou!\n Enviando para: - Email"; 18 | var messageTwo = "O Sistema falhou!\n Enviando para: - Email - Slack"; 19 | var messageThree = "O Sistema falhou!\n Enviando para: - Email - Slack - Facebook"; 20 | 21 | Assert.Equal(messageOne, decorator.GetMessage()); 22 | Assert.Equal(messageTwo, decorator2.GetMessage()); 23 | Assert.Equal(messageThree, decorator3.GetMessage()); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DesignPatterns.Tests/DesignPatterns.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | all 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /DesignPatterns.Tests/FactoryTest.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Creatinal.Factory; 2 | using Xunit; 3 | 4 | namespace DesignPatterns.Tests 5 | { 6 | public class FactoryTest 7 | { 8 | [Fact] 9 | public void ShouldGetDriver() 10 | { 11 | var person = PersonFactory.CreatePerson("Joao", cnh: 123); 12 | 13 | Assert.Equal(typeof(Driver), person.GetType()); 14 | } 15 | 16 | [Fact] 17 | public void ShouldGetVender() 18 | { 19 | var person = PersonFactory.CreatePerson("Joao", license: 123); 20 | 21 | Assert.Equal(typeof(Pilot), person.GetType()); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /DesignPatterns.Tests/SingletonTest.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Creatinal.Singleton; 2 | using Xunit; 3 | 4 | namespace DesignPatterns.Tests 5 | { 6 | public class SingletonTest 7 | { 8 | [Fact] 9 | public void ShouldGetInstance() 10 | { 11 | var instance = Singleton.GetInstance(); 12 | var newInstance = Singleton.GetInstance(); 13 | 14 | Assert.Equal(instance.ToString(), newInstance.ToString()); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /DesignPatterns.Tests/StrategyTest.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Behavorial.Strategy; 2 | using Xunit; 3 | 4 | namespace DesignPatterns.Tests 5 | { 6 | public class StrategyTest 7 | { 8 | [Fact] 9 | public void ShouldGenerateCommissionBasic() 10 | { 11 | var employee = new Employee(EmployeeType.Representative, "Gabriel Pereira", new CommissionBasic()); 12 | var order = new Order(employee, 1000); 13 | 14 | Assert.Equal(10, order.GetCommission()); 15 | } 16 | 17 | [Fact] 18 | public void ShouldGenerateCommissionMiddle() 19 | { 20 | var employee = new Employee(EmployeeType.Vendor, "Isabel Sophia", new CommissionMiddle()); 21 | var order = new Order(employee, 1000); 22 | 23 | Assert.Equal(20, order.GetCommission()); 24 | } 25 | 26 | [Fact] 27 | public void ShouldGenerateCommissionFull() 28 | { 29 | var employee = new Employee(EmployeeType.Manager, "Davi Pereira", new CommissionFull()); 30 | var order = new Order(employee, 1000); 31 | 32 | Assert.Equal(30, order.GetCommission()); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /DesignPatterns.Tests/TemplateMethodTest.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns. Behavorial.TemplateMethod; 2 | using Xunit; 3 | 4 | namespace DesignPatterns.Tests 5 | { 6 | public class TemplateMethodTest 7 | { 8 | [Fact] 9 | public void ShouldSignIn() 10 | { 11 | var user = new User("admin@email.com", "123456", ServerType.Gmail); 12 | 13 | var login = new GoogleAuth(); 14 | _ = login.SignIn(user); 15 | var information = login.GetUserInformation(); 16 | 17 | Assert.NotNull(information); 18 | Assert.Equal(user.Email, information.Email); 19 | Assert.Equal(user.ServerType, information.ServerType); 20 | } 21 | 22 | [Fact] 23 | public void ShouldNotSignIn() 24 | { 25 | var user = new User("admin@email.com", "123456", ServerType.Gmail); 26 | 27 | var login = new GitHubAuth(); 28 | _ = login.SignIn(user); 29 | var information = login.GetUserInformation(); 30 | 31 | Assert.Null(information); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /DesignPatterns.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DesignPatterns", "DesignPatterns\DesignPatterns.csproj", "{66175A6B-CBC9-4E00-BF87-33DF62A2E102}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DesignPatterns.Tests", "DesignPatterns.Tests\DesignPatterns.Tests.csproj", "{49211850-5339-45AA-B210-9CA6253ADB81}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(SolutionProperties) = preSolution 16 | HideSolutionNode = FALSE 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {66175A6B-CBC9-4E00-BF87-33DF62A2E102}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {66175A6B-CBC9-4E00-BF87-33DF62A2E102}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {66175A6B-CBC9-4E00-BF87-33DF62A2E102}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {66175A6B-CBC9-4E00-BF87-33DF62A2E102}.Release|Any CPU.Build.0 = Release|Any CPU 23 | {49211850-5339-45AA-B210-9CA6253ADB81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {49211850-5339-45AA-B210-9CA6253ADB81}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {49211850-5339-45AA-B210-9CA6253ADB81}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {49211850-5339-45AA-B210-9CA6253ADB81}.Release|Any CPU.Build.0 = Release|Any CPU 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Bridge/IConsole.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Bridge 2 | { 3 | public interface IConsole 4 | { 5 | public bool Enable { get; set; } 6 | public bool JoystickA { get; set; } 7 | 8 | bool IsOn(); 9 | bool JoystickIsConnected(); 10 | bool Shutdown(); 11 | bool Startup(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Bridge/JoystickAdvanced.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Bridge 2 | { 3 | public class JoystickAdvanced : JoystickBasic 4 | { 5 | public JoystickAdvanced(IConsole console) : base(console) { } 6 | 7 | public bool ShutdownConsole() 8 | { 9 | if (Console.IsOn()) 10 | { 11 | return !Console.Shutdown(); 12 | } 13 | 14 | return false; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Bridge/JoystickBasic.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Bridge 2 | { 3 | public class JoystickBasic 4 | { 5 | public IConsole Console { get; set; } 6 | 7 | public JoystickBasic(IConsole console) 8 | { 9 | Console = console; 10 | } 11 | 12 | 13 | public bool ConectOnConsole() 14 | { 15 | if (!Console.JoystickIsConnected()) 16 | { 17 | Console.JoystickA = true; 18 | } 19 | 20 | return Console.JoystickIsConnected(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Bridge/PlayStation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DesignPatterns.Behavorial.Bridge 4 | { 5 | public class PlayStation : IConsole 6 | { 7 | public bool Enable { get; set; } = false; 8 | public bool JoystickA { get; set; } = false; 9 | 10 | public bool IsOn() => Enable; 11 | 12 | public bool JoystickIsConnected() => JoystickA; 13 | 14 | public bool Shutdown() 15 | { 16 | Enable = false; 17 | 18 | return Enable; 19 | } 20 | 21 | public bool Startup() 22 | { 23 | Enable = true; 24 | 25 | return Enable; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Bridge/XBox.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Bridge 2 | { 3 | public class XBox : IConsole 4 | { 5 | public bool Enable { get; set; } = false; 6 | public bool JoystickA { get; set; } = false; 7 | 8 | public bool IsOn() => Enable; 9 | 10 | public bool JoystickIsConnected() => JoystickA; 11 | 12 | public bool Shutdown() 13 | { 14 | Enable = false; 15 | 16 | return Enable; 17 | } 18 | 19 | public bool Startup() 20 | { 21 | Enable = true; 22 | 23 | return Enable; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Decorator/Componet/Notifier.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Behavorial.Decorator.Interface; 2 | 3 | namespace DesignPatterns.Decorator.Componet 4 | { 5 | public class Notifier : INotifier 6 | { 7 | 8 | public string Message { get; } 9 | 10 | public Notifier(string message) 11 | { 12 | Message = message; 13 | } 14 | 15 | public virtual string GetMessage() 16 | { 17 | return Message + "\n Enviando para:"; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Decorator/Decorator/BaseDecorator.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Behavorial.Decorator.Interface; 2 | 3 | namespace DesignPatterns.Decorator 4 | { 5 | public class BaseDecorator : INotifier 6 | { 7 | public INotifier Wrappee { get; private set; } 8 | 9 | public BaseDecorator(INotifier wrappee) 10 | { 11 | Wrappee = wrappee; 12 | } 13 | 14 | public virtual string GetMessage() 15 | { 16 | return $"{Wrappee.GetMessage()} - Email"; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Decorator/Decorator/FacebookDecorator.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Behavorial.Decorator.Interface; 2 | 3 | namespace DesignPatterns.Decorator 4 | { 5 | public class FacebookDecorator : BaseDecorator 6 | { 7 | 8 | public FacebookDecorator(INotifier wrappee) : base(wrappee) 9 | { 10 | } 11 | 12 | public override string GetMessage() 13 | { 14 | return $"{Wrappee.GetMessage()} - Facebook"; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Decorator/Decorator/SlackDecorator.cs: -------------------------------------------------------------------------------- 1 | using DesignPatterns.Behavorial.Decorator.Interface; 2 | 3 | namespace DesignPatterns.Decorator 4 | { 5 | public class SlackDecorator : BaseDecorator 6 | { 7 | public SlackDecorator(INotifier wrappee) 8 | :base(wrappee) 9 | { 10 | } 11 | 12 | public override string GetMessage() 13 | { 14 | return $"{Wrappee.GetMessage()} - Slack"; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Decorator/Interface/INotifier.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Decorator.Interface 2 | { 3 | public interface INotifier 4 | { 5 | string GetMessage(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Strategy/Commission.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Strategy 2 | { 3 | public class CommissionBasic : ICommission 4 | { 5 | public decimal GetValue(Order order) => order.TotalValue * 0.01M; 6 | } 7 | 8 | public class CommissionMiddle : ICommission 9 | { 10 | public decimal GetValue(Order order) => order.TotalValue * 0.02M; 11 | } 12 | 13 | public class CommissionFull : ICommission 14 | { 15 | public decimal GetValue(Order order) => order.TotalValue * 0.03M; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Strategy/Employee.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Strategy 2 | { 3 | public class Employee 4 | { 5 | public EmployeeType Type { get; set; } 6 | public string FullName { get; set; } 7 | public ICommission Commission { get; private set; } 8 | 9 | public Employee(EmployeeType type, string fullName, ICommission commission) 10 | { 11 | Type = type; 12 | FullName = fullName; 13 | Commission = commission; 14 | } 15 | } 16 | 17 | public enum EmployeeType 18 | { 19 | Representative = 1, 20 | Vendor = 2, 21 | Manager = 3 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Strategy/ICommission.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Strategy 2 | { 3 | public interface ICommission 4 | { 5 | decimal GetValue(Order order); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/Strategy/Order.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.Strategy 2 | { 3 | public class Order 4 | { 5 | public Employee Employee { get; set; } 6 | public decimal TotalValue { get; set; } 7 | 8 | public Order(Employee employee, decimal totalValue) 9 | { 10 | TotalValue = totalValue; 11 | Employee = employee; 12 | } 13 | 14 | public decimal GetCommission() => Employee.Commission.GetValue(this); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/TemplateMethod/GitHubAuth.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.TemplateMethod 2 | { 3 | public class GitHubAuth : Login 4 | { 5 | public override bool SignIn(User user) 6 | { 7 | if (user.ServerType != ServerType.GitHub) return IsAuthenticated(); 8 | 9 | User = user; 10 | 11 | return IsAuthenticated(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/TemplateMethod/GoogleAuth.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.TemplateMethod 2 | { 3 | public class GoogleAuth : Login 4 | { 5 | public override bool SignIn(User user) 6 | { 7 | if (user.ServerType != ServerType.Gmail) return IsAuthenticated(); 8 | 9 | User = user; 10 | 11 | return IsAuthenticated(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/TemplateMethod/Login.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.TemplateMethod 2 | { 3 | public abstract class Login 4 | { 5 | public User User { get; set; } 6 | 7 | public abstract bool SignIn(User user); 8 | 9 | public bool IsAuthenticated() => User != null; 10 | 11 | public User GetUserInformation() => User; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /DesignPatterns/Behavorial/TemplateMethod/User.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Behavorial.TemplateMethod 2 | { 3 | public class User 4 | { 5 | public string Email { get; set; } 6 | public string Password { get; set; } 7 | public ServerType ServerType { get; set; } 8 | 9 | public User(string email, string password, ServerType serverType) 10 | { 11 | Email = email; 12 | Password = password; 13 | ServerType = serverType; 14 | } 15 | } 16 | 17 | public enum ServerType 18 | { 19 | Gmail = 1, 20 | GitHub = 2 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /DesignPatterns/Creatinal/Builder/Director.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Creatinal.Builder 2 | { 3 | public class Director 4 | { 5 | public VehicleBuilder VehicleBuilder; 6 | 7 | public Director(VehicleBuilder vehicleBuilder) 8 | { 9 | VehicleBuilder = vehicleBuilder; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /DesignPatterns/Creatinal/Builder/Vehicle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DesignPatterns.Creatinal.Builder 4 | { 5 | public class Vehicle 6 | { 7 | public string Description { get; set; } 8 | public DateTime ManufacturingYear { get; set; } 9 | public VehicleType VehicleType { get; set; } 10 | public decimal Value { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /DesignPatterns/Creatinal/Builder/VehicleBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DesignPatterns.Creatinal.Builder 4 | { 5 | public class CarBuilder : VehicleBuilder 6 | { 7 | public CarBuilder(string x, DateTime y, decimal v) 8 | { 9 | Init(); 10 | Build(x, y, v); 11 | BuildType(); 12 | } 13 | 14 | public override void BuildType() 15 | { 16 | Vehicle.VehicleType = VehicleType.Automobile; 17 | } 18 | } 19 | 20 | public class MotocycleBuilder : VehicleBuilder 21 | { 22 | public MotocycleBuilder(string x, DateTime y, decimal v) 23 | { 24 | Init(); 25 | Build(x, y, v); 26 | BuildType(); 27 | } 28 | 29 | public override void BuildType() 30 | { 31 | Vehicle.VehicleType = VehicleType.Motocycle; 32 | } 33 | } 34 | 35 | public abstract class VehicleBuilder 36 | { 37 | protected Vehicle Vehicle; 38 | 39 | 40 | protected void Init() 41 | { 42 | Vehicle = new Vehicle(); 43 | } 44 | 45 | public Vehicle GetVehicle() 46 | { 47 | return Vehicle; 48 | } 49 | 50 | public abstract void BuildType(); 51 | 52 | protected void Build(string description, DateTime date, decimal value) 53 | { 54 | Vehicle.Value = value; 55 | Vehicle.Description = description; 56 | Vehicle.ManufacturingYear = date; 57 | } 58 | } 59 | 60 | public enum VehicleType 61 | { 62 | Motocycle = 4, 63 | Automobile = 7, 64 | } 65 | } -------------------------------------------------------------------------------- /DesignPatterns/Creatinal/Factory/Driver.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Creatinal.Factory 2 | { 3 | public class Driver : Person 4 | { 5 | public int CNH { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /DesignPatterns/Creatinal/Factory/Person.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DesignPatterns.Creatinal.Factory 4 | { 5 | public abstract class Person 6 | { 7 | public int Id { get; set; } 8 | public string FullName { get; set; } 9 | public DateTime CreatedAt { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /DesignPatterns/Creatinal/Factory/PersonFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DesignPatterns.Creatinal.Factory 4 | { 5 | public abstract class PersonFactory 6 | { 7 | public static Person CreatePerson(string fullName, int? cnh = null, int? license = null) 8 | { 9 | if (license != null) 10 | { 11 | return new Pilot 12 | { 13 | FullName = fullName, 14 | License = license.Value 15 | }; 16 | } 17 | else if (cnh != null) 18 | { 19 | return new Driver 20 | { 21 | CNH = cnh.Value, 22 | FullName = fullName 23 | }; 24 | } 25 | else 26 | { 27 | throw new NotImplementedException(); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /DesignPatterns/Creatinal/Factory/Pilot.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Creatinal.Factory 2 | { 3 | public class Pilot : Person 4 | { 5 | public int License { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /DesignPatterns/Creatinal/Singleton/Singleton.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DesignPatterns.Creatinal.Singleton 4 | { 5 | public class Singleton 6 | { 7 | private string Id = Guid.NewGuid().ToString(); 8 | private static Singleton Instance; 9 | 10 | private Singleton() {} 11 | 12 | public static Singleton GetInstance() 13 | { 14 | if (Instance == null) 15 | { 16 | Instance = new Singleton(); 17 | } 18 | 19 | return Instance; 20 | } 21 | 22 | public override string ToString() 23 | { 24 | return Id; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /DesignPatterns/DesignPatterns.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /DesignPatterns/Structure/Adapter/AdapterLogger.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Structure.Adapter 2 | { 3 | public class AdapterLogger : ILogger 4 | { 5 | private readonly ICustomLogger _customLogger; 6 | 7 | public AdapterLogger(ICustomLogger customLogger) 8 | { 9 | _customLogger = customLogger; 10 | } 11 | 12 | public void LogInformation(string message) 13 | { 14 | _customLogger.LogInfo(message); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /DesignPatterns/Structure/Adapter/CustomLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DesignPatterns.Structure.Adapter 4 | { 5 | public class CustomLogger : ICustomLogger 6 | { 7 | public void LogInfo(string message) 8 | { 9 | Console.WriteLine($"CUSTOM LOG: {message}"); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /DesignPatterns/Structure/Adapter/ICustomLogger.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Structure.Adapter 2 | { 3 | public interface ICustomLogger 4 | { 5 | void LogInfo(string message); 6 | } 7 | } -------------------------------------------------------------------------------- /DesignPatterns/Structure/Adapter/ILogger.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Structure.Adapter 2 | { 3 | public interface ILogger 4 | { 5 | void LogInformation(string message); 6 | } 7 | } -------------------------------------------------------------------------------- /DesignPatterns/Structure/Adapter/Logger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DesignPatterns.Structure.Adapter 4 | { 5 | public class Logger : ILogger 6 | { 7 | public void LogInformation(string message) 8 | { 9 | Console.WriteLine($"LOG: {message}"); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /DesignPatterns/Structure/Adapter/Service.cs: -------------------------------------------------------------------------------- 1 | namespace DesignPatterns.Structure.Adapter 2 | { 3 | public class Service 4 | { 5 | private readonly ILogger _logger; 6 | 7 | public Service(ILogger logger) 8 | { 9 | _logger = logger; 10 | } 11 | 12 | public override string ToString() 13 | { 14 | _logger.LogInformation("Transação"); 15 | 16 | return string.Empty; 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **Patterns** 2 | É um repositório para estudo de **Padrões de Projetos**. Baseado nos 23 padrões catalogados pela *Gang of Four* (GoF), irei apresentar os padrões *Comportamenstais, Estruturais e de Criação* utilizando a linguagem C#. 3 | 4 | **Creational Patterns** 5 | - [x] [Factory Method](https://github.com/jlfjunior/patterns#factorymethod) 6 | - [x] [Builder](https://github.com/jlfjunior/patterns#builder) 7 | - [ ] Prototype 8 | - [ ] Abstract Factory 9 | - [x] [Singleton](https://github.com/jlfjunior/patterns#singleton) 10 | 11 | **Structural Patterns** 12 | - [x] [Adapter](https://github.com/jlfjunior/design-patterns#adapter) 13 | - [ ] Decorator 14 | - [ ] Composite 15 | - [x] [Bridge](https://github.com/jlfjunior/patterns#bridge) 16 | - [ ] Facade 17 | - [ ] Proxy 18 | - [ ] Flyweight 19 | 20 | **Behavioral Patterns** 21 | - [x] [Template Method](https://github.com/jlfjunior/patterns#templatemethod) 22 | - [x] [Strategy](https://github.com/jlfjunior/patterns#strategy) 23 | - [ ] Observer 24 | - [ ] Command 25 | - [ ] Mediator 26 | - [ ] Iterator 27 | - [ ] Chain of Responsibility 28 | - [ ] Memento 29 | - [ ] State 30 | - [ ] Visitor 31 | 32 | ### Strategy 33 | O *Strategy* é um padrão que pode ser utilizado quando uma classe principal possuir diversos algoritmos que podem ser alterados para contemplar um comportamento específico. 34 | 35 | Pontos Positivos 36 | - Alterar o algoritmo sem alterar a classe principal. 37 | - Redução de lógicas complexas dentro da classe principal. 38 | - A implementação pode ser alterada em tempo de execução. 39 | - Fortalece Open/Closed Principle presente no S.O.L.I.D. Você pode implementar novas estrategia sem alterar a classe principal 40 | 41 | Pontos Negativos 42 | - Aumento da complexidade da criação de objetos. 43 | - Aumento do número de classes para a solução. 44 | 45 | ### TemplateMethod 46 | O *Template Method* define um modelo/esqueleto para uma classe base, deixando que suas sub classes implementem partes do seu algoritmo ou reescrevam determinadas etapas do seu algoritmo sem alterar o modelo/esqueleto pré definido. 47 | 48 | Pontos Positivos 49 | - Permite que os clientes subscrevam partes do algoritmo, incluindo/removendo regras. 50 | - Concentração do código comum na superclasse. 51 | 52 | Pontos Negativos 53 | - Usa herança, ferindo o Liskov Substitution Principle (LSP) presente no S.O.L.I.D 54 | 55 | ### FactoryMethod 56 | O *Factory Method* é um padrão que consiste em definir uma interface para criar objetos em um superclasse, porém esse padrão permite que as subclasses alterem o tipo do objeto quando necessário. 57 | 58 | Pontos Positivos 59 | - Evita acoplamento forte dentro do sistema. 60 | - Princípio de responsabilidade única. Você concentra o código de criação de objetos em um único método. 61 | - Princípio aberto/fechado. Você pode introduzir novos tipos do mesmo objeto no programa sem quebrar o código cliente existente. 62 | 63 | Pontos Negativos 64 | - Aumento do número de subclasses para a solução. 65 | 66 | ### Adapter 67 | O *Adapter* pode ser utilizado quando precisamos compatibilizar uma interface não suportada por um serviço em uma que é suportada pelo serviço sem que o mesmo seja alterado. 68 | 69 | Pontos Positivos 70 | - Preserva o cenceito de Single Responsible Principle (SRP) sugerido pelo S.O.L.I.D 71 | - Preserva o conceito de Open/Closed principle OCP, pois o serviço consumidor não sofre alteração 72 | 73 | Pontos Negativos 74 | - Sua base de código aumenta porque é necessario adicionar uma interface e sua implementação para torna as interfaces compativeis com o a que é esperada pelo serviço consumidor. 75 | 76 | ### Bridge 77 | O *Bridge* é um padrão que permite que você faça uma ponte entre dois conjuntos de classes intimamente ligados através da composição de uma interface comum. Dessa forma você pode desenvolver cada extremidade independentemente sem afetar a ligação entre elas. 78 | 79 | Pontos Positivos 80 | - Você cria classes e abstrações independentes. 81 | - O código cliente trabalha com abstrações de alto nível sem se preocupar com detalhes da plataforma. 82 | - Princípio de responsabilidade única. Foco na lógica de alto nível na abstração e detalhes específicos na implementação. 83 | 84 | Pontos Negativos 85 | - Você torna o código mais complexo de entender ao aplicar o padrão em uma classe altamente coesa. 86 | 87 | ### Singleton 88 | O *Singleton* é um padrão que pode ser utilizado quando o desenvolvedor deseja ter um ponto de acesso único a uma instância de uma classe no projeto. 89 | 90 | Pontos Positivos 91 | - Um objeto singleton só é instanciado quando for requisitado pela primeira vez. 92 | - Você ganha um ponto único de acesso a uma instância. 93 | - O desenvolvedor tem certeza que uma classe tem uma única instância. 94 | 95 | Pontos Negativos 96 | - O Singleton resolve dois problemas, violando o princípio de responsabilidade única. 97 | - O Singleton requer tratamento especial em um ambiente multithreaded. 98 | - Aumento da complexidade de realizar testes unitários. 99 | 100 | ### Builder 101 | O *Builder* é um padrão muito utilizado quando o desenvolvedor tem a necessidade de dividir em etapas a criação de objetos complexos da sua representação. O padrão ainda permite a construção de diferentes representações de um mesmo objeto. 102 | 103 | Pontos Positivos 104 | - Princípio de responsabilidade única. O desenvolvedor isola a complexidade de construção do objeto das regras de negócios. 105 | - Reaproveitamento de código, é possível usar os passos comuns a diferentes objetos. 106 | 107 | Pontos Negativos 108 | - Aumenta a complexidade de código devido a criação de novas classes. 109 | 110 | # Reference 111 | - [DoFactory](https://www.dofactory.com/net/design-patterns) 112 | - [Factoring.Guru](https://refactoring.guru/design-patterns) --------------------------------------------------------------------------------