├── .gitignore ├── .mailmap ├── Architectural patterns ├── model-view-controller │ ├── Java │ │ ├── MVCPattern.java │ │ ├── Student.java │ │ ├── StudentController.java │ │ └── StudentView.java │ ├── JavaScript │ │ ├── controller.js │ │ ├── index.html │ │ ├── model.js │ │ └── view.js │ └── readme.md └── service_locator │ ├── Java │ ├── ServiceLocator.java │ └── service-locator │ │ ├── Cache.java │ │ ├── InitialContext.java │ │ ├── README.md │ │ ├── Service.java │ │ ├── Service1.java │ │ ├── Service2.java │ │ ├── ServiceLocator.java │ │ └── ServiceLocatorPatternDemo.java │ └── readme.md ├── Behavioral ├── Callback │ ├── README.md │ ├── Ruby │ │ └── callback.rb │ ├── cpp │ │ └── callback.cpp │ ├── java │ │ └── CallbackDemo.java │ ├── javascript │ │ └── callback.js │ ├── kotlin │ │ └── CallbackDemo.kt │ ├── python │ │ └── callback_demo.py │ ├── swift │ │ └── callback.swift │ └── typescript │ │ └── callback.ts ├── ChainOfResponsability │ ├── C# │ │ └── ChainOfResponsibility.cs │ ├── C++ │ │ ├── ChainOfResponsibility.cpp │ │ └── ChainPattern.cpp │ ├── Go │ │ └── chain_of_ responsibility.go │ ├── Java │ │ ├── ChainOfResponsability.java │ │ └── com │ │ │ └── chain │ │ │ └── resposibility │ │ │ ├── ATMDispenseChain.java │ │ │ ├── Currency.java │ │ │ ├── DispenseChain.java │ │ │ ├── FiftyDollarDispense.java │ │ │ ├── TenDollarDispense.java │ │ │ └── TwentyDollarDispense.java │ ├── Python │ │ └── ChainOfResponsibility.py │ ├── README.md │ ├── php │ │ └── chain.php │ ├── swift │ │ └── ChainOfResponsability.swift │ └── typescript │ │ └── chain.ts ├── Command │ ├── C# │ │ ├── CommandPattern.csproj │ │ ├── Concretes │ │ │ ├── CloseSwitchCommand.cs │ │ │ ├── Light.cs │ │ │ ├── OpenSwitchCommand.cs │ │ │ └── Switch.cs │ │ ├── Interfaces │ │ │ ├── ICommand.cs │ │ │ └── ISwitchable.cs │ │ ├── Program.cs │ │ └── README.md │ ├── C++ │ │ └── CommandPattern.cpp │ ├── Go │ │ └── command.go │ ├── Java │ │ ├── Clear.java │ │ ├── Command.java │ │ ├── CommandPatternDemo.java │ │ ├── Edit.java │ │ ├── LowerCase.java │ │ ├── TextEditor.java │ │ ├── TextField.java │ │ └── UpperCase.java │ ├── README.md │ ├── Ruby │ │ └── command.rb │ ├── Swift │ │ └── Command.swift │ ├── javascript │ │ └── command.js │ ├── kotlin │ │ └── Command.kt │ ├── php │ │ └── command.php │ └── python │ │ └── command.py ├── Delegation │ ├── README.md │ ├── java │ │ └── Delegation.java │ ├── kotlin │ │ ├── delegation.kt │ │ └── delegation2.kt │ ├── pyhton │ │ └── delegation.py │ └── typescript │ │ └── delegation.ts ├── Interpreter │ ├── C++ │ │ └── InterpreterPattern.cpp │ ├── README.md │ ├── c# │ │ └── Interpreter │ │ │ └── Program.cs │ ├── java │ │ ├── Expression.java │ │ ├── IntToBinaryExpression.java │ │ ├── IntToHexExpression.java │ │ ├── InterpreterClient.java │ │ └── InterpreterContext.java │ ├── kotlin │ │ └── interpreter.kts │ └── python │ │ ├── calcs.py │ │ └── operations.py ├── Iterator │ ├── Go │ │ └── iterator.go │ ├── README.md │ ├── c++11 │ │ └── iterator.cpp │ ├── csharp │ │ └── iterator.cs │ ├── java │ │ ├── CollectionOfDouble.java │ │ ├── IteratorDemo.java │ │ ├── IteratorGenerics.java │ │ ├── IteratorOfDouble.java │ │ ├── ListOfDouble.java │ │ └── ListOfDoubleIterator.java │ ├── javascript │ │ └── iterator.js │ ├── kotlin │ │ └── Iterator.kt │ ├── php │ │ └── iterator.php │ └── python │ │ └── iterator.py ├── Mediator │ ├── csharp │ │ └── mediator.cs │ ├── java │ │ ├── MediatorEx.java │ │ └── mediatorCar.java │ ├── javascript │ │ └── mediator.js │ ├── kotlin │ │ └── mediator.kt │ ├── php │ │ └── mediator.php │ ├── python │ │ └── mediator.py │ ├── readme.md │ └── scala │ │ └── MediatorExample.scala ├── Memento │ ├── Java │ │ ├── FileWriterCaretaker.java │ │ ├── FileWriterClient.java │ │ └── FileWriterUtil.java │ ├── README.md │ ├── csharp │ │ └── Memento.cs │ ├── javascript │ │ └── Memento.js │ ├── kotlin │ │ └── main.kts │ ├── php │ │ └── momento.php │ ├── python │ │ └── memento.py │ ├── ruby │ │ ├── caretaker.rb │ │ ├── memento.rb │ │ └── originator.rb │ └── rust │ │ └── memento.rs ├── NullObject │ ├── CSharp │ │ ├── Bicycle.cs │ │ ├── Car.cs │ │ ├── Engine.cs │ │ ├── Motorcycle.cs │ │ ├── Program.cs │ │ └── Vehicle.cs │ ├── Go │ │ └── null_object.go │ ├── Java │ │ ├── AbstractDrink.java │ │ ├── DrinkManager.java │ │ ├── NullDrink.java │ │ ├── NullObjectPatternDemo.java │ │ └── RealDrink.java │ └── README.md ├── Observer │ ├── Cpp │ │ ├── GraphObserver.cpp │ │ ├── GraphObserver.h │ │ ├── Group.cpp │ │ ├── Group.h │ │ ├── Observer .cpp │ │ ├── Observer.h │ │ ├── TableObserver.cpp │ │ ├── TableObserver.h │ │ └── main.cpp │ ├── Go │ │ └── observer.go │ ├── Java │ │ └── ObserverDemo.java │ ├── JavaScript │ │ └── observer.js │ ├── Kotlin │ │ ├── observer.kt │ │ └── observer2.kt │ ├── PublishSubscribePattern │ │ ├── README.md │ │ └── pubSub.js │ ├── Python │ │ └── observer.py │ ├── README.md │ ├── Ruby │ │ └── observer.rb │ ├── Swift │ │ └── Observer.swift │ ├── VB │ │ └── observer.vb │ ├── csharp │ │ └── observer.cs │ ├── java │ │ ├── CitizenObserver.java │ │ ├── ObserverDesignPattern.java │ │ ├── RestaurantObserver.java │ │ ├── WeatherObserver.java │ │ ├── WeatherSubject.java │ │ └── WeatherType.java │ ├── php │ │ └── observer.php │ └── typescript │ │ └── observer.ts ├── README.md ├── State │ ├── C++ │ │ └── statepattern.cpp │ ├── Go │ │ └── keyboard_state.go │ ├── README.md │ ├── c# │ │ └── Program.cs │ ├── java │ │ ├── CalculateState.java │ │ ├── CashierState.java │ │ ├── CollectMoneyState.java │ │ ├── FinishState.java │ │ ├── README.md │ │ ├── ScanGoodsState.java │ │ ├── StartState.java │ │ ├── StateContext.java │ │ └── StatePatternDemo.java │ ├── kotlin │ │ └── State.kt │ ├── php │ │ └── state.php │ ├── python │ │ └── state_demo.py │ └── typescript │ │ └── state.ts ├── Strategy │ ├── C# │ │ ├── Bus.cs │ │ ├── Program.cs │ │ ├── PublicTransport.cs │ │ ├── Strategy.cs │ │ └── Train.cs │ ├── Go │ │ └── sorting_strategy.go │ ├── README.md │ ├── Swift │ │ ├── LoggerStrategy.swift │ │ └── Strategy.swift │ ├── cpp │ │ ├── BillingStrategy.hpp │ │ ├── Demo.cpp │ │ ├── DiscountStrategy.hpp │ │ ├── NormalStrategy.hpp │ │ └── Product.hpp │ ├── go │ │ └── Strategy.go │ ├── java │ │ ├── Aluguel.java │ │ ├── BillingStrategy.java │ │ ├── Cliente.java │ │ ├── DiscountStrategy.java │ │ ├── Discounter.java │ │ ├── DiscounterDemo.java │ │ ├── Fita.java │ │ ├── FitaInfantil.java │ │ ├── FitaLancamento.java │ │ ├── FitaNormal.java │ │ ├── NormalStrategy.java │ │ ├── Product.java │ │ ├── StrategyDemo.java │ │ ├── TipoFita.java │ │ ├── basket │ │ │ └── app │ │ │ │ ├── BasketPriceCounter.java │ │ │ │ ├── Product.java │ │ │ │ ├── ShoppingBasketApp.java │ │ │ │ └── strategies │ │ │ │ ├── FruitsDiscountStrategy.java │ │ │ │ ├── NormalPricesStrategy.java │ │ │ │ ├── PriceCounterStrategy.java │ │ │ │ └── TeaDiscountStrategy.java │ │ ├── medievalstrategy │ │ │ ├── ArmyKeyAsset.java │ │ │ ├── MedievalStrategy.java │ │ │ ├── WarLord.java │ │ │ ├── WarStrategy.java │ │ │ └── strategies │ │ │ │ ├── CallTheTanks.java │ │ │ │ ├── DestroyTheGate.java │ │ │ │ └── UseTheSecretPassage.java │ │ └── strategy_arithmetical_operations │ │ │ ├── README.md │ │ │ ├── images │ │ │ └── strategy_pattern.png │ │ │ ├── pom.xml │ │ │ └── src │ │ │ └── main │ │ │ └── java │ │ │ └── com │ │ │ └── mycompany │ │ │ └── strategy_arithmetical_operations │ │ │ ├── CalculatorClient.java │ │ │ ├── CalculatorContext.java │ │ │ ├── ConcreteStrategyAdd.java │ │ │ ├── ConcreteStrategyMultiply.java │ │ │ ├── ConcreteStrategySubstract.java │ │ │ ├── Strategy.java │ │ │ └── Strategy_arithmetical_operations.java │ ├── javascript │ │ ├── administration.js │ │ ├── developer.js │ │ ├── employee.js │ │ └── index.js │ ├── kotlin │ │ ├── FunctionalStrategy.kt │ │ └── Strategy.kt │ ├── php │ │ └── strategy.php │ ├── python │ │ ├── sorting_strategies.py │ │ └── strategy_demo.py │ ├── scala │ │ └── Strategy.scala │ └── typescript │ │ └── strategy.ts ├── TemplateMethod │ ├── README.md │ ├── c# │ │ ├── BaseOrder.cs │ │ ├── DerivedOrder1.cs │ │ ├── DerivedOrder2.cs │ │ └── Program.cs │ ├── c++ │ │ ├── Operation.h │ │ ├── Subtraction.h │ │ ├── Sum.h │ │ └── main.cpp │ ├── go │ │ └── template_method.go │ ├── java │ │ ├── Defender.java │ │ ├── Goalkeeper.java │ │ ├── Midfielder.java │ │ ├── Player.java │ │ ├── TemplateMethod.java │ │ └── TemplateMethodDemo.java │ ├── javascript │ │ └── template-method.js │ ├── kotlin │ │ ├── CaffeineBeverage.kt │ │ ├── Coffee.kt │ │ ├── Tea.kt │ │ └── TemplateMethodDemo.kt │ ├── php │ │ └── template.php │ ├── python │ │ ├── prepare_shake.py │ │ └── template_example.py │ └── swift │ │ └── template.swift └── Visitor │ ├── README.md │ ├── cpp │ ├── main.cpp │ ├── products.cpp │ ├── visitor.cpp │ └── visitor.h │ ├── csharp │ └── Program.cs │ ├── java │ ├── Circle.java │ ├── PrintAreaVisitor.java │ ├── Rectangle.java │ ├── Shape.java │ ├── ShapeVisitor.java │ └── VisitorDemo.java │ ├── javascript │ └── Visitor.js │ ├── kotlin │ └── VisitorDemo.kt │ ├── php │ └── visitor.php │ ├── python │ └── visitor.py │ └── scala │ └── Visitor.scala ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Concurrency ├── Active Object │ └── java │ │ ├── AOBookingDemo.java │ │ └── ActiveObject.java ├── Balking Pattern │ ├── Documentation.md │ └── java │ │ └── BalkingPattern.java ├── Concurrent Server │ ├── go │ │ └── concurrent_server │ │ │ ├── Readme.md │ │ │ ├── client │ │ │ └── main │ │ │ │ └── tcp_client.go │ │ │ └── server │ │ │ ├── main │ │ │ └── tcp_server.go │ │ │ └── thread │ │ │ └── server_thread.go │ └── java │ │ ├── Client.java │ │ ├── MainServer.java │ │ ├── README.md │ │ └── ServerThread.java ├── Creational │ └── Singleton │ │ └── java │ │ ├── DoubleCheckSingletonPattern.java │ │ └── SingletonLazyThreadSafe.java ├── Fan In │ └── go │ │ ├── fanIn.go │ │ └── readme.md ├── Fan Out │ └── kotlin │ │ └── FanOutProducer.kt ├── Guarded Suspension │ └── java │ │ └── GuardedSuspension.java ├── Mutex │ └── Mutex │ │ ├── go │ │ └── mutex.go │ │ └── java │ │ ├── Bank.java │ │ ├── Mutex.java │ │ ├── MutexExample.java │ │ └── Theif.java ├── Observer │ ├── README.md │ ├── java │ │ └── ObserverConcurrencyDemo.java │ ├── php │ │ ├── Observable.php │ │ ├── Observer.php │ │ └── Test.php │ └── python │ │ ├── Launcher.py │ │ ├── Publisher.py │ │ └── Subscriber.py ├── Semaphores │ └── java │ │ └── Semaphores │ │ ├── Semaphore.java │ │ ├── multiplex │ │ ├── Multiplex.java │ │ └── MultiplexThread.java │ │ ├── mutex │ │ ├── Mutex.java │ │ └── MutexThread.java │ │ ├── rendezVouz │ │ ├── RendezVouz.java │ │ └── RendezVouzThread.java │ │ └── signaling │ │ ├── Signaling.java │ │ └── SignalingThread.java └── ThreadPool │ ├── csharp │ └── ThreadPoolExample.cs │ ├── go │ ├── Readme.md │ └── threadpool.go │ └── java │ └── ThreadPool.java ├── Creational ├── Abstract Factory │ ├── README.md │ ├── cpp │ │ └── abstract-factory.cpp │ ├── csharp │ │ ├── AbstractFactoryUML.PNG │ │ ├── csharp.sln │ │ └── csharp │ │ │ ├── Cars │ │ │ ├── Car.cs │ │ │ ├── Models │ │ │ │ ├── Astra.cs │ │ │ │ └── Corsa.cs │ │ │ ├── Opel.cs │ │ │ └── Properties │ │ │ │ ├── Color.cs │ │ │ │ └── Model.cs │ │ │ ├── Factory │ │ │ ├── AbstractFactory.cs │ │ │ └── CarFactory.cs │ │ │ ├── Program.cs │ │ │ └── csharp.csproj │ ├── go │ │ └── abstractfactory.go │ ├── java │ │ ├── CalculatorFactory │ │ │ ├── Add.java │ │ │ ├── Calculator.java │ │ │ ├── CreateCalculator.java │ │ │ ├── Divide.java │ │ │ ├── GetCalcFactory.java │ │ │ ├── Multiply.java │ │ │ ├── Power.java │ │ │ └── Subtract.java │ │ ├── FactoryPattern.jpg │ │ ├── FatoryPattern.java │ │ ├── Vehicle.java │ │ ├── VehicleFactory.java │ │ └── example1 │ │ │ ├── App.java │ │ │ ├── FactoryCar.java │ │ │ ├── GMCFactory.java │ │ │ ├── Minivan.java │ │ │ ├── Pickup.java │ │ │ ├── Savana.java │ │ │ ├── Sienna.java │ │ │ ├── Sierra.java │ │ │ ├── Tacoma.java │ │ │ ├── ToyotaFactory.java │ │ │ └── readme.md │ ├── kotlin │ │ └── AbstractFactory.kt │ ├── php │ │ ├── abstract-factory.php │ │ └── abstract_factory.php │ ├── python │ │ └── abstract_factory.py │ └── typescript │ │ └── abstract_factory.ts ├── Builder │ ├── Csharp │ │ ├── CarWithNormalBuilder.cs │ │ └── Program.cs │ ├── README.md │ ├── Ruby │ │ └── builder.rb │ ├── cpp │ │ └── BuilderPattern.cpp │ ├── elixir │ │ └── house_builder.ex │ ├── go │ │ └── builder.go │ ├── java │ │ ├── Box.java │ │ ├── BuildAHouse.java │ │ ├── BuilderPattern.java │ │ ├── BuilderWithLombok.java │ │ ├── Car.java │ │ ├── Developer.java │ │ ├── DeveloperBuildUsage.java │ │ ├── EffectiveJavaBuilderPattern.java │ │ ├── HouseExample.java │ │ ├── ImmutableBuilderEx.java │ │ ├── InvoiceData.java │ │ └── Person.java │ ├── javascript │ │ ├── README.md │ │ ├── builderPattern.js │ │ └── builderPatternEs6.js │ ├── kotlin │ │ └── BuilderPattern.kt │ ├── php │ │ └── builder.php │ ├── python │ │ └── BuilderPattern.py │ ├── rust │ │ └── builder.rs │ ├── scala │ │ └── Builder.scala │ ├── swift │ │ └── Builder.swift │ └── typescript │ │ └── buider.ts ├── Constructor │ ├── README.md │ ├── cpp │ │ └── constructor.cpp │ ├── csharp │ │ └── Constructor.cs │ ├── java │ │ ├── Constructor.java │ │ └── PrivateConstructor.java │ ├── javaScript │ │ └── constructor.js │ ├── python │ │ └── constructor.py │ ├── ruby │ │ └── constructor.rb │ └── swift │ │ └── constructor.swift ├── Dependency Injection │ ├── CSharp │ │ ├── .gitignore │ │ ├── DI_Example.csproj │ │ ├── DI_Example.sln │ │ ├── Program.cs │ │ └── global.json │ ├── README.md │ ├── java │ │ └── DependencyInjectorPattern.java │ ├── python │ │ └── DI.py │ └── typescript │ │ ├── di.ts │ │ └── ioc-di.ts ├── Factory-Method-PT[BR] │ ├── factory_method.py │ └── readme.md ├── Factory-Method │ ├── Java │ │ ├── IPizzeria.java │ │ ├── Main.java │ │ ├── MiPizzeria.java │ │ ├── Pizza.java │ │ └── PizzaOrillaRellena.java │ ├── README.md │ ├── cSharp │ │ ├── Program.cs │ │ └── Vehicle.cs │ ├── php │ │ ├── factory-method.php │ │ └── maria-factory-method.php │ ├── python │ │ └── FactoryMethod.py │ └── typescript │ │ └── factory-method.ts ├── Factory │ ├── C# │ │ └── FactoryPattern.cs │ ├── C++ │ │ ├── factory.cpp │ │ └── factory.h │ ├── Dart │ │ └── factory.dart │ ├── README.md │ ├── d │ │ └── Logger.d │ ├── elixir │ │ └── shape_factory.ex │ ├── go │ │ ├── book_factory.go │ │ └── factory_pattern.go │ ├── java │ │ ├── Car.java │ │ ├── Chassis.java │ │ ├── Circle.java │ │ ├── Engine.java │ │ ├── ExteriorFeature.java │ │ ├── FactoryPatternDemo.java │ │ ├── Feature.java │ │ ├── InteriorFeature.java │ │ ├── ManufacturedEngine.java │ │ ├── Rectangle.java │ │ ├── Shape.java │ │ ├── ShapeFactory.java │ │ ├── Square.java │ │ ├── TestFactory.java │ │ ├── Vehicle.java │ │ ├── VehicleChassis.java │ │ └── VehicleFrame.java │ ├── javaScript │ │ └── factory.js │ ├── kotlin │ │ ├── Factory.kt │ │ └── FactoryPatternDemo.kt │ ├── php │ │ └── Book.php │ ├── python │ │ ├── Readme.md │ │ └── factory.py │ ├── ruby │ │ ├── README.md │ │ └── factory.rb │ ├── swift │ │ └── factory.swift │ └── typescript │ │ └── factoryMethod.ts ├── LazyInitialization │ ├── C# │ │ └── LazyInitialization.cs │ ├── README.md │ ├── java │ │ ├── LazyInitializationPattern.java │ │ ├── Vehicle.java │ │ └── transactions-history │ │ │ ├── CurrentYearLazyLoadingTransactionLogsIterator.java │ │ │ ├── TransactionLog.java │ │ │ ├── TransactionLogApp.java │ │ │ └── TransactionLogsDAO.java │ ├── kotlin │ │ ├── DeferVariableAssignment.kt │ │ └── LazyInitializationPattern.kt │ └── python │ │ └── vehicle.py ├── Method Chaining │ ├── Golang │ │ └── Method_Chaining.go │ ├── README.md │ ├── cpp │ │ └── MethodChaining.cpp │ ├── csharp │ │ └── MethodChaining.cs │ ├── dlang │ │ └── method_chaining.d │ ├── java │ │ ├── CreationWithFlowApi.java │ │ └── MethodChaining.java │ ├── javascript │ │ └── method_chaning.js │ ├── kotlin │ │ └── main.kts │ ├── perl │ │ ├── Rectangle.pm │ │ └── method_chaining.pl │ ├── php │ │ └── MethodChaining.php │ ├── python │ │ └── method_chaining.py │ └── ruby │ │ └── method_chaining.rb ├── Module │ ├── README.md │ └── javaScript │ │ └── module.js ├── Multiton │ ├── README.md │ └── java │ │ ├── Multiton.java │ │ └── MultitonTest.java ├── ObjectPool │ ├── README.md │ ├── java │ │ ├── JDBCConnectionPool.java │ │ ├── Object.java │ │ └── ObjectPool.java │ └── python │ │ └── ObjectPool.py ├── Prototype │ ├── README.md │ ├── java │ │ ├── EmployeeRecord.java │ │ ├── Prototype.java │ │ └── PrototypeDemo.java │ ├── javascript │ │ ├── README.md │ │ └── prototype.js │ ├── kotlin │ │ └── prototype.kt │ └── php │ │ └── Prototype.php ├── SimpleFactory │ ├── java │ │ ├── CheesePizza.java │ │ ├── ClamPizza.java │ │ ├── PepperoniPizza.java │ │ ├── Pizza.java │ │ ├── PizzaStore.java │ │ ├── SimplePizzaFactory.java │ │ ├── VeggiePizza.java │ │ └── readme.md │ ├── kotlin │ │ └── main.kts │ ├── php │ │ └── SimpleFactory.php │ ├── ruby │ │ └── simple_factory.rb │ └── typescript │ │ └── simple-factory.ts ├── Singleton │ ├── README.md │ ├── cpp │ │ ├── SingletonDesignPattern.cpp │ │ ├── SingletonDesignPattern.h │ │ └── main.cpp │ ├── csharp │ │ ├── SingletonDesignPattern.cs │ │ └── SingletonPattern with Thread safety.cs │ ├── go │ │ └── singleton.go │ ├── golang │ │ ├── README.md │ │ └── Singleton.go │ ├── groovy │ │ ├── singleton.groovy │ │ └── singletonLazyInitialisation.groovy │ ├── java │ │ ├── AboutSingleton.txt │ │ ├── AddTwoNumbersSingleton.java │ │ ├── Singleton.java │ │ ├── SingletonDesignPattern.java │ │ ├── SingletonEager.java │ │ ├── SingletonSimple.java │ │ ├── SingletonSynchronizedBlock.java │ │ ├── SingletonSynchronizedMethod.java │ │ ├── SingletonUsingInnerStaticClass.java │ │ ├── StaticBlockSingleton.java │ │ ├── ThreadSafeSingleton.java │ │ └── singleton.java │ ├── javaScript │ │ └── singleton.js │ ├── kotlin │ │ ├── LazySingletonDesignPattern.kt │ │ └── SingletonDesignPattern.kt │ ├── objective-c │ │ ├── Singleton.h │ │ └── Singleton.m │ ├── php │ │ ├── Singleton.php │ │ └── SingletonDesignPattern.php │ ├── python │ │ └── singleton.py │ ├── ruby │ │ ├── README.md │ │ ├── example.rb │ │ └── logger.rb │ ├── scala │ │ ├── Singleton.scala │ │ └── SingletonCounter.scala │ ├── swift │ │ └── Singleton.swift │ └── typescript │ │ └── singleton.ts └── Value Object │ ├── README.md │ ├── java │ └── ValueObject.java │ ├── kotlin │ └── ValueObject.kt │ └── typescript │ └── value-object.ts ├── FrontController ├── README.md └── java │ ├── Dispatcher.java │ ├── FrontController.java │ ├── FrontControllerPatternDemo.java │ ├── GoHome.java │ └── GoTution.java ├── ISSUE_TEMPLATE.md ├── Miscellaneous ├── DAO │ ├── C# │ │ └── DAO │ │ │ ├── Implementation │ │ │ └── MonsterDAOImpl.cs │ │ │ ├── Interfaces │ │ │ └── MonsterDAO.cs │ │ │ ├── Monster.cs │ │ │ └── Program.cs │ └── java │ │ ├── BookDAO.java │ │ ├── BookDAOImpl.java │ │ ├── Books.java │ │ ├── DAO.png │ │ └── README.md ├── DependencyInjection │ ├── C# │ │ └── DependencyInjection │ │ │ ├── Concretes │ │ │ ├── AudioManager.cs │ │ │ ├── GameManager.cs │ │ │ └── SceneManager.cs │ │ │ ├── Interfaces │ │ │ ├── IAudioManager.cs │ │ │ └── ISceneManager.cs │ │ │ └── Program.cs │ └── java │ │ ├── EmailService.java │ │ ├── MyApplication.java │ │ └── MyLegactTest.java ├── RulesEngine │ └── C# │ │ └── RulesEngine │ │ ├── CardUtilities │ │ └── CardContext.cs │ │ ├── GameObjects │ │ ├── BaseCard.cs │ │ ├── ItemCard.cs │ │ └── MonsterCard.cs │ │ ├── Interfaces │ │ └── ICardRule.cs │ │ ├── Player.cs │ │ ├── Program.cs │ │ ├── Rules │ │ ├── FortificationBoostLifeRule.cs │ │ ├── MechanicalBlastShieldRule.cs │ │ └── UndeadSpectralTouchRule.cs │ │ └── RulesEngine.cs └── Strategy │ └── js │ └── strategy.js ├── Structural ├── AbstactDocument │ └── java │ │ ├── AbstractDocument.java │ │ └── Document.java ├── Adapter │ ├── README.md │ ├── c# │ │ ├── IXmlToJson.cs │ │ ├── JsonConverter.cs │ │ ├── Manufacturer.cs │ │ ├── ManufacturerDataProvider.cs │ │ ├── Program.cs │ │ ├── XmlConverter.cs │ │ └── XmlToJsonAdapter.cs │ ├── c++ │ │ ├── adapter.h │ │ └── dlist.h │ ├── go │ │ └── adapter.go │ ├── java │ │ ├── AnimalAdapterDemo.java │ │ ├── ShapeAdapterDemo.java │ │ └── example1 │ │ │ ├── AppAfter.java │ │ │ ├── AppBofere.java │ │ │ ├── Desktop.java │ │ │ ├── Device.java │ │ │ ├── Mobile.java │ │ │ ├── Mobile.java~ │ │ │ ├── MobileAdapter.java │ │ │ └── Notebook.java │ ├── javascript │ │ └── adapter.js │ ├── kotlin │ │ └── AdapterDesignPattern.kt │ ├── php │ │ └── adapter.php │ ├── python │ │ └── adapter.py │ ├── ruby │ │ ├── README.md │ │ └── adapter.rb │ ├── rust │ │ └── adapter.rs │ └── vb │ │ └── adapter.vb ├── Bridge │ ├── C# │ │ └── BridgePattern │ │ │ ├── Monster.cs │ │ │ ├── Mutator.cs │ │ │ └── Program.cs │ ├── java │ │ ├── BridgeDemo.java │ │ ├── Color.java │ │ ├── GreenColor.java │ │ ├── Pentagon.java │ │ ├── RedColor.java │ │ ├── Shape.java │ │ └── Triangle.java │ ├── kotlin │ │ └── BridgePattern.kt │ ├── php │ │ └── bridge.php │ ├── python │ │ └── BridgePattern.py │ ├── scala │ │ └── BridgePattern.scala │ └── typescript │ │ └── bridge.ts ├── Builder │ ├── BuilderPattern.java │ ├── HowToUse.java │ ├── README.md │ ├── User.java │ └── kotlin │ │ └── builder.kts ├── Composite │ ├── C# │ │ ├── 1 │ │ │ ├── Leaf.cs │ │ │ ├── Program.cs │ │ │ ├── Tree.cs │ │ │ └── TreeComponent.cs │ │ └── 2 │ │ │ ├── File.cs │ │ │ ├── Folder.cs │ │ │ └── IComponent.cs │ ├── Kotlin │ │ └── composite.kt │ ├── java │ │ ├── CompositeDemo.java │ │ ├── Developer.java │ │ ├── Employee.java │ │ ├── Manager.java │ │ └── employecompositedemo.java │ ├── php │ │ └── composite.php │ ├── python │ │ └── CompositePattern.py │ ├── scala │ │ └── CompositePattern.scala │ └── typescript │ │ └── composite.ts ├── Decorator │ ├── README.md │ ├── c# │ │ └── DecoratorPattern.cs │ ├── cpp │ │ └── decorator.cpp │ ├── decorator.java │ ├── java │ │ ├── DecoratorDesignPattern.java │ │ └── decorator.java │ ├── javascript │ │ └── Coffee.js │ ├── kotlin │ │ └── Decorator.kt │ ├── php │ │ └── decorator.php │ ├── python │ │ ├── Readme.md │ │ └── decorator.py │ ├── ruby │ │ └── decorator.rb │ ├── rust │ │ └── decorator.rs │ └── typescript │ │ ├── decorator-experimental.ts │ │ └── decorator.ts ├── Facade │ ├── C# │ │ ├── Food.cs │ │ ├── Hamburger.cs │ │ ├── Pizza.cs │ │ ├── Program.cs │ │ ├── Spaghetti.cs │ │ └── Waiter.cs │ ├── README.md │ ├── d │ │ └── facade.d │ ├── go │ │ └── facade.go │ ├── java │ │ ├── Blackberry.java │ │ ├── FacadePatternClient.java │ │ ├── Iphone.java │ │ ├── MobileShop.java │ │ ├── Samsung.java │ │ └── ShopKeeper.java │ ├── javaScript │ │ └── facade.js │ ├── kotlin │ │ ├── FacadePattern.kt │ │ └── using facade design pattern for bank service.png │ ├── php │ │ └── facade.php │ ├── python │ │ └── facade.py │ ├── rust │ │ └── facade.rs │ └── typescript │ │ └── facade.ts ├── Filter │ └── java │ │ ├── AndCriteria.java │ │ ├── Criteria.java │ │ ├── CriteriaFemale.java │ │ ├── CriteriaMale.java │ │ ├── CriteriaSingle.java │ │ ├── FilterDemo.java │ │ ├── OrCriteria.java │ │ ├── Person.java │ │ ├── filter_pattern_uml_diagram.jpg │ │ └── readme.md ├── Flyweight │ ├── c# │ │ └── Flightweight │ │ │ └── Program.cs │ ├── go │ │ └── flyweight.go │ ├── java │ │ ├── ColorBox.java │ │ ├── FlyweightDemo.java │ │ └── shape-circle-demo │ │ │ ├── Circle.java │ │ │ ├── FlyweightDemo.java │ │ │ ├── README.md │ │ │ ├── Shape.java │ │ │ └── ShapeFactory.java │ ├── php │ │ └── flyweight.php │ ├── python │ │ └── FlyWheight.py │ ├── readme.md │ └── scala │ │ └── Flywheight.scala ├── PrivateClass │ ├── c# │ │ └── Circle.cs │ ├── golang │ │ ├── car │ │ │ └── car.go │ │ └── main.go │ ├── java │ │ └── SalaryCalculator.java │ ├── kotlin │ │ └── SalaryCalculator.kt │ ├── python │ │ └── Private_Class_Data.py │ └── readme.md ├── Proxy │ ├── README.md │ ├── csharp │ │ └── proxy.cs │ ├── java │ │ ├── AccessLimitingTextFile.java │ │ ├── CachedTextFile.java │ │ ├── ProxyDemo.java │ │ ├── RemoteTextFile.java │ │ └── TextFile.java │ ├── javascript │ │ └── proxy.js │ ├── kotlin │ │ └── CachedImage.kt │ ├── php │ │ └── proxy.php │ ├── python │ │ └── calculator.py │ └── ruby │ │ └── proxy.rb ├── Repository │ ├── csharp │ │ ├── ExampleEntitie.cs │ │ ├── ExampleRepository.cs │ │ ├── IDefaultRepository.cs │ │ └── UsingRepository.cs │ ├── java │ │ ├── Product.java │ │ ├── ProductRepository.java │ │ ├── ProductRepositoryDefault.java │ │ ├── Repository.java │ │ └── RepositoryDefault.java │ ├── kotlin │ │ └── repository.kts │ ├── readme.md │ └── typescript │ │ └── repository.ts └── TransactionalStack │ └── Java │ ├── IntStackTransactional.java │ └── TransactionalIntStack.java ├── media ├── design-patterns.jpeg └── facade.png └── readme.md /.mailmap: -------------------------------------------------------------------------------- 1 | 2 | Joseph Cagle 3 | Joseph Cagle 4 | 5 | -------------------------------------------------------------------------------- /Architectural patterns/model-view-controller/Java/MVCPattern.java: -------------------------------------------------------------------------------- 1 | public static void main(String[] args) 2 | { 3 | Student model = retriveStudentFromDatabase(); 4 | 5 | StudentView view = new StudentView(); 6 | 7 | StudentController controller = new StudentController(model, view); 8 | 9 | controller.updateView(); 10 | 11 | controller.setStudentName("Vikram Sharma"); 12 | 13 | controller.updateView(); 14 | } 15 | 16 | private static Student retriveStudentFromDatabase() 17 | { 18 | Student student = new Student(); 19 | student.setName("Lokesh Sharma"); 20 | student.setRollNo("15UCS157"); 21 | return student; 22 | } -------------------------------------------------------------------------------- /Architectural patterns/model-view-controller/Java/Student.java: -------------------------------------------------------------------------------- 1 | class Student 2 | { 3 | private String rollNo; 4 | private String name; 5 | 6 | public String getRollNo() 7 | { 8 | return rollNo; 9 | } 10 | 11 | public void setRollNo(String rollNo) 12 | { 13 | this.rollNo = rollNo; 14 | } 15 | 16 | public String getName() 17 | { 18 | return name; 19 | } 20 | 21 | public void setName(String name) 22 | { 23 | this.name = name; 24 | } 25 | } -------------------------------------------------------------------------------- /Architectural patterns/model-view-controller/Java/StudentView.java: -------------------------------------------------------------------------------- 1 | class StudentView 2 | { 3 | public void printStudentDetails(String studentName, String studentRollNo) 4 | { 5 | System.out.println("Student: "); 6 | System.out.println("Name: " + studentName); 7 | System.out.println("Roll No: " + studentRollNo); 8 | } 9 | } -------------------------------------------------------------------------------- /Architectural patterns/model-view-controller/JavaScript/controller.js: -------------------------------------------------------------------------------- 1 | window.onload = function () { 2 | let view = new View(); 3 | let ship = new PirateShip(); 4 | let controller = new Controller(view, ship); 5 | controller.bindListeners(); 6 | }; 7 | 8 | let Controller = function (display, model) { 9 | this.display = display; 10 | this.model = model; 11 | } 12 | 13 | Controller.prototype = { 14 | bindListeners() { 15 | let button = this.display.getButton(); 16 | button.addEventListener('click', this.moveModel.bind(this)); 17 | }, 18 | 19 | moveModel() { 20 | this.model.incrementLocation(); 21 | let newLocation = this.model.location; 22 | this.display.setShipLocation(newLocation); 23 | }, 24 | }; 25 | -------------------------------------------------------------------------------- /Architectural patterns/model-view-controller/JavaScript/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Architectural patterns/model-view-controller/JavaScript/model.js: -------------------------------------------------------------------------------- 1 | let PirateShip = function () { 2 | this.location = 0; 3 | }; 4 | 5 | PirateShip.prototype.incrementLocation = function () { 6 | this.location += 10; 7 | }; 8 | -------------------------------------------------------------------------------- /Architectural patterns/model-view-controller/JavaScript/view.js: -------------------------------------------------------------------------------- 1 | let View = function () { 2 | this.shipSelector = '#pirateShipImage'; 3 | this.buttonSelector = 'button'; 4 | }; 5 | 6 | View.prototype = { 7 | getShip() { 8 | return document.querySelector(this.shipSelector); 9 | }, 10 | setShipLocation(location) { 11 | let ship = this.getShip(); 12 | ship.style.left = location; 13 | }, 14 | getButton() { 15 | return document.querySelector(this.buttonSelector) 16 | }, 17 | }; -------------------------------------------------------------------------------- /Architectural patterns/service_locator/Java/service-locator/Cache.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Cache { 5 | 6 | private List services = new ArrayList(); 7 | 8 | public Service getService(String serviceName){ 9 | 10 | for(Service service:services){ 11 | if(service.getName().equalsIgnoreCase(serviceName)) 12 | return service; 13 | } 14 | return null; 15 | } 16 | public void addService(Service service) { 17 | services.add(service); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Architectural patterns/service_locator/Java/service-locator/InitialContext.java: -------------------------------------------------------------------------------- 1 | 2 | public class InitialContext { 3 | 4 | public Object lookup(String jndiName) { 5 | 6 | if("Service1".equalsIgnoreCase(jndiName)){ 7 | return new Service1(); 8 | } 9 | else if("Service2".equalsIgnoreCase(jndiName)) { 10 | return new Service2(); 11 | } 12 | else { 13 | System.out.println("Jndi name "+jndiName+" not configured please check logs"); 14 | return null; 15 | } 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Architectural patterns/service_locator/Java/service-locator/README.md: -------------------------------------------------------------------------------- 1 | #Service Locator Pattern 2 | 3 | Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server. 4 | 5 | Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose. 6 | 7 | Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services. 8 | 9 | Cache - Cache to store references of services to reuse them 10 | 11 | Client - Client is the object that invokes the services via ServiceLocator. -------------------------------------------------------------------------------- /Architectural patterns/service_locator/Java/service-locator/Service.java: -------------------------------------------------------------------------------- 1 | 2 | public interface Service { 3 | 4 | String getName(); 5 | void execute(); 6 | } 7 | -------------------------------------------------------------------------------- /Architectural patterns/service_locator/Java/service-locator/Service1.java: -------------------------------------------------------------------------------- 1 | 2 | public class Service1 implements Service { 3 | 4 | @Override 5 | public String getName() { 6 | return "Service1"; 7 | } 8 | 9 | @Override 10 | public void execute() { 11 | 12 | System.out.println("Service executed "+getName()); 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Architectural patterns/service_locator/Java/service-locator/Service2.java: -------------------------------------------------------------------------------- 1 | 2 | public class Service2 implements Service { 3 | 4 | @Override 5 | public String getName() { 6 | return "Service2"; 7 | } 8 | 9 | @Override 10 | public void execute() { 11 | System.out.println("Executing service "+getName()); 12 | 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Architectural patterns/service_locator/Java/service-locator/ServiceLocator.java: -------------------------------------------------------------------------------- 1 | 2 | public class ServiceLocator { 3 | 4 | private static Cache cache; 5 | 6 | static { 7 | cache = new Cache(); 8 | } 9 | public static Service getService(String jndiName) { 10 | 11 | Service service = cache.getService(jndiName); 12 | if(service != null) 13 | { 14 | System.out.println("returned object from cache"); 15 | return service; 16 | } 17 | 18 | service = (Service) new InitialContext().lookup(jndiName); 19 | cache.addService(service); 20 | return service; 21 | 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Architectural patterns/service_locator/Java/service-locator/ServiceLocatorPatternDemo.java: -------------------------------------------------------------------------------- 1 | 2 | public class ServiceLocatorPatternDemo { 3 | 4 | public static void main(String [] args) { 5 | 6 | Service service = new ServiceLocator().getService("Service1"); 7 | service.execute(); 8 | 9 | service = new ServiceLocator().getService("Service2"); 10 | service.execute(); 11 | 12 | service = new ServiceLocator().getService("Service1"); 13 | service.execute(); 14 | 15 | service = new ServiceLocator().getService("Service2"); 16 | service.execute(); 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Behavioral/Callback/Ruby/callback.rb: -------------------------------------------------------------------------------- 1 | # This is a traditional example of a callback in Ruby but it is not idiomatic. 2 | def finished_homework(subject) 3 | p "Finished my #{subject} homework." 4 | end 5 | 6 | def do_homework(subject, callback) 7 | p "Starting my #{subject} homework." 8 | callback.call(subject) 9 | end 10 | 11 | do_homework("Math", method(:finished_homework)) 12 | 13 | # To perform an idiomatic ruby callback, the block syntax is used 14 | def do_homework(subject, &block) 15 | p "Starting my #{subject} homework." 16 | yield subject 17 | end 18 | 19 | do_homework("Math") do |subject| 20 | p "Finished my #{subject} homework." 21 | end 22 | -------------------------------------------------------------------------------- /Behavioral/Callback/cpp/callback.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct CallbackHandler { 6 | 7 | virtual void onCallback() = 0; 8 | }; 9 | 10 | struct MyCallbackHandler : public CallbackHandler { 11 | 12 | virtual void onCallback() { 13 | cout << "Callback was invoked!\n"; 14 | } 15 | }; 16 | 17 | void apply(CallbackHandler* handler) { 18 | cout << "Inside a function that accepts a callback.\n"; 19 | 20 | handler->onCallback(); 21 | } 22 | 23 | int main() { 24 | cout << "Invoke a function that accepts a callback.\n"; 25 | 26 | MyCallbackHandler handler; 27 | apply(&handler); 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Behavioral/Callback/java/CallbackDemo.java: -------------------------------------------------------------------------------- 1 | interface CallbackHandler { 2 | void onCallback(); 3 | } 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | System.out.println("calling a function with callback defined"); 8 | myFunction(new CallbackHandler() { 9 | @Override 10 | public void onCallback() { 11 | System.out.println("got callback"); 12 | } 13 | }); 14 | } 15 | 16 | static void myFunction(CallbackHandler callbackHandler) { 17 | // do something ... 18 | System.out.println("function called"); 19 | 20 | // callback 21 | callbackHandler.onCallback(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Behavioral/Callback/javascript/callback.js: -------------------------------------------------------------------------------- 1 | function doHomework(subject, callback) { 2 | alert(`Starting my ${subject} homework.`); 3 | callback(); 4 | } 5 | function alertFinished(){ 6 | alert('Finished my homework'); 7 | } 8 | 9 | doHomework('math', alertFinished); 10 | -------------------------------------------------------------------------------- /Behavioral/Callback/python/callback_demo.py: -------------------------------------------------------------------------------- 1 | def callback_fun(): 2 | print("got callback") 3 | pass 4 | 5 | 6 | def my_fun(callback): 7 | print("function called") 8 | callback() 9 | pass 10 | 11 | 12 | def main(): 13 | print("call a function with callback") 14 | my_fun(callback_fun) 15 | pass 16 | 17 | 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /Behavioral/Callback/typescript/callback.ts: -------------------------------------------------------------------------------- 1 | export namespace callbackExample { 2 | export const sum = (...numbers: number[]) => numbers.reduce((x, y) => x + y) 3 | export const sub = (...numbers: number[]) => numbers.reduce((x, y) => x - y) 4 | 5 | function calc12345(name: string, op: CallableFunction): void { 6 | console.log(`Hello ${name}!`) 7 | console.log(`Calc ${op.toString()} = ${op(1, 2, 3, 4, 5)}`) 8 | } 9 | 10 | calc12345('Mike', sum) 11 | calc12345('John', sub) 12 | } 13 | -------------------------------------------------------------------------------- /Behavioral/ChainOfResponsability/Java/com/chain/resposibility/Currency.java: -------------------------------------------------------------------------------- 1 | package com.chain.resposibility; 2 | 3 | public class Currency { 4 | 5 | private int amount; 6 | 7 | public Currency(int amt){ 8 | this.amount=amt; 9 | } 10 | 11 | public int getAmount(){ 12 | return this.amount; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Behavioral/ChainOfResponsability/Java/com/chain/resposibility/DispenseChain.java: -------------------------------------------------------------------------------- 1 | package com.chain.resposibility; 2 | 3 | public interface DispenseChain { 4 | 5 | void setNextChain(DispenseChain nextChain); 6 | 7 | void dispense(Currency cur); 8 | } 9 | -------------------------------------------------------------------------------- /Behavioral/ChainOfResponsability/Java/com/chain/resposibility/FiftyDollarDispense.java: -------------------------------------------------------------------------------- 1 | package com.chain.resposibility; 2 | 3 | 4 | public class FiftyDollarDispense implements DispenseChain { 5 | 6 | private DispenseChain chain; 7 | 8 | @Override 9 | public void setNextChain(DispenseChain nextChain) { 10 | this.chain=nextChain; 11 | } 12 | 13 | @Override 14 | public void dispense(Currency cur) { 15 | if(cur.getAmount() >= 50){ 16 | int num = cur.getAmount()/50; 17 | int remainder = cur.getAmount() % 50; 18 | System.out.println("Dispensing "+num+" 50$ note"); 19 | if(remainder !=0) this.chain.dispense(new Currency(remainder)); 20 | }else{ 21 | this.chain.dispense(cur); 22 | } 23 | 24 | } 25 | 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Behavioral/ChainOfResponsability/Java/com/chain/resposibility/TenDollarDispense.java: -------------------------------------------------------------------------------- 1 | package com.chain.resposibility; 2 | 3 | public class TenDollarDispense implements DispenseChain { 4 | 5 | private DispenseChain chain; 6 | 7 | @Override 8 | public void setNextChain(DispenseChain nextChain) { 9 | this.chain=nextChain; 10 | } 11 | 12 | @Override 13 | public void dispense(Currency cur) { 14 | if(cur.getAmount() >= 10){ 15 | int num = cur.getAmount()/10; 16 | int remainder = cur.getAmount() % 10; 17 | System.out.println("Dispensing "+num+" 10$ note"); 18 | if(remainder !=0) this.chain.dispense(new Currency(remainder)); 19 | }else{ 20 | this.chain.dispense(cur); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Behavioral/ChainOfResponsability/Java/com/chain/resposibility/TwentyDollarDispense.java: -------------------------------------------------------------------------------- 1 | package com.chain.resposibility; 2 | 3 | public class TwentyDollarDispense implements DispenseChain { 4 | 5 | private DispenseChain chain; 6 | 7 | @Override 8 | public void setNextChain(DispenseChain nextChain) { 9 | this.chain=nextChain; 10 | } 11 | 12 | @Override 13 | public void dispense(Currency cur) { 14 | if(cur.getAmount() >= 20){ 15 | int num = cur.getAmount()/20; 16 | int remainder = cur.getAmount() % 20; 17 | System.out.println("Dispensing "+num+" 20$ note"); 18 | if(remainder !=0) this.chain.dispense(new Currency(remainder)); 19 | }else{ 20 | this.chain.dispense(cur); 21 | } 22 | 23 | } 24 | 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Behavioral/Command/C#/CommandPattern.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp1.1 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Behavioral/Command/C#/Concretes/CloseSwitchCommand.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern 2 | { 3 | /* The Command for turning on the device - ConcreteCommand #1 */ 4 | public class CloseSwitchCommand : ICommand 5 | { 6 | private ISwitchable _switchable; 7 | 8 | public CloseSwitchCommand(ISwitchable switchable) 9 | { 10 | _switchable = switchable; 11 | } 12 | 13 | public void Execute() 14 | { 15 | _switchable.PowerOn(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Behavioral/Command/C#/Concretes/Light.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CommandPattern 4 | { 5 | /* The Receiver class */ 6 | public class Light : ISwitchable 7 | { 8 | public void PowerOn() 9 | { 10 | Console.WriteLine("The light is on"); 11 | } 12 | 13 | public void PowerOff() 14 | { 15 | Console.WriteLine("The light is off"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Behavioral/Command/C#/Concretes/OpenSwitchCommand.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern 2 | { 3 | /* The Command for turning off the device - ConcreteCommand #2 */ 4 | public class OpenSwitchCommand : ICommand 5 | { 6 | private ISwitchable _switchable; 7 | 8 | public OpenSwitchCommand(ISwitchable switchable) 9 | { 10 | _switchable = switchable; 11 | } 12 | 13 | public void Execute() 14 | { 15 | _switchable.PowerOff(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Behavioral/Command/C#/Concretes/Switch.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern 2 | { 3 | /* The Invoker class */ 4 | public class Switch 5 | { 6 | ICommand _closedCommand; 7 | ICommand _openedCommand; 8 | 9 | public Switch(ICommand closedCommand, ICommand openedCommand) 10 | { 11 | this._closedCommand = closedCommand; 12 | this._openedCommand = openedCommand; 13 | } 14 | 15 | //close the circuit/power on 16 | public void Close() 17 | { 18 | this._closedCommand.Execute(); 19 | } 20 | 21 | //open the circuit/power off 22 | public void Open() 23 | { 24 | this._openedCommand.Execute(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Behavioral/Command/C#/Interfaces/ICommand.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern 2 | { 3 | public interface ICommand 4 | { 5 | void Execute(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Behavioral/Command/C#/Interfaces/ISwitchable.cs: -------------------------------------------------------------------------------- 1 | namespace CommandPattern 2 | { 3 | /* An interface that defines actions that the receiver can perform */ 4 | public interface ISwitchable 5 | { 6 | void PowerOn(); 7 | void PowerOff(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Behavioral/Command/Java/Clear.java: -------------------------------------------------------------------------------- 1 | public class Clear extends Command { 2 | 3 | @Override 4 | public void execute(TextField textField) { 5 | textField.setText(null); 6 | } 7 | 8 | @Override 9 | public String toString() { 10 | return "Clear"; 11 | } 12 | } -------------------------------------------------------------------------------- /Behavioral/Command/Java/Edit.java: -------------------------------------------------------------------------------- 1 | public class Edit extends Command { 2 | 3 | private final String value; 4 | 5 | public Edit(String value) { 6 | this.value = value; 7 | } 8 | 9 | @Override 10 | public void execute(TextField textField) { 11 | textField.setText(value); 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return "Edit text"; 17 | } 18 | } -------------------------------------------------------------------------------- /Behavioral/Command/Java/LowerCase.java: -------------------------------------------------------------------------------- 1 | public class LowerCase extends Command { 2 | 3 | @Override 4 | public void execute(TextField textField) { 5 | if (textField.getText() != null) { 6 | textField.setText(textField.getText().toLowerCase()); 7 | } 8 | } 9 | 10 | @Override 11 | public String toString() { 12 | return "Lower case"; 13 | } 14 | } -------------------------------------------------------------------------------- /Behavioral/Command/Java/TextField.java: -------------------------------------------------------------------------------- 1 | public class TextField { 2 | 3 | private String text; 4 | 5 | public TextField(String text) { 6 | this.text = text; 7 | } 8 | 9 | public String getText() { 10 | return text; 11 | } 12 | 13 | public void setText(String text) { 14 | this.text = text; 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return text; 20 | } 21 | } -------------------------------------------------------------------------------- /Behavioral/Command/Java/UpperCase.java: -------------------------------------------------------------------------------- 1 | public class UpperCase extends Command { 2 | 3 | @Override 4 | public void execute(TextField textField) { 5 | if (textField.getText() != null) { 6 | textField.setText(textField.getText().toUpperCase()); 7 | } 8 | } 9 | 10 | @Override 11 | public String toString() { 12 | return "Upper case"; 13 | } 14 | } -------------------------------------------------------------------------------- /Behavioral/Interpreter/README.md: -------------------------------------------------------------------------------- 1 | # Interpreter design pattern 2 | 3 | Interpreter pattern is used to defines a grammatical representation for a language and provides an 4 | interpreter to deal with this grammar. 5 | 6 | The best example of interpreter design pattern is java compiler that interprets the java source code 7 | into byte code that is understandable by JVM. Google Translator is also an example of interpreter pattern where the input can be in any language and we can get the output interpreted in another language. -------------------------------------------------------------------------------- /Behavioral/Interpreter/java/Expression.java: -------------------------------------------------------------------------------- 1 | public interface Expression { 2 | 3 | String interpret(InterpreterContext ic); 4 | } -------------------------------------------------------------------------------- /Behavioral/Interpreter/java/IntToBinaryExpression.java: -------------------------------------------------------------------------------- 1 | public class IntToBinaryExpression implements Expression { 2 | 3 | private int i; 4 | 5 | public IntToBinaryExpression(int c){ 6 | this.i=c; 7 | } 8 | @Override 9 | public String interpret(InterpreterContext ic) { 10 | return ic.getBinaryFormat(this.i); 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /Behavioral/Interpreter/java/IntToHexExpression.java: -------------------------------------------------------------------------------- 1 | public class IntToHexExpression implements Expression { 2 | 3 | private int i; 4 | 5 | public IntToHexExpression(int c){ 6 | this.i=c; 7 | } 8 | 9 | @Override 10 | public String interpret(InterpreterContext ic) { 11 | return ic.getHexadecimalFormat(i); 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /Behavioral/Interpreter/java/InterpreterContext.java: -------------------------------------------------------------------------------- 1 | public class InterpreterContext { 2 | 3 | public String getBinaryFormat(int i){ 4 | return Integer.toBinaryString(i); 5 | } 6 | 7 | public String getHexadecimalFormat(int i){ 8 | return Integer.toHexString(i); 9 | } 10 | } -------------------------------------------------------------------------------- /Behavioral/Interpreter/python/calcs.py: -------------------------------------------------------------------------------- 1 | from operations import Number, Sum, Subtraction, Multiplication, Division 2 | 3 | 4 | if __name__ == '__main__': 5 | five_minus_three = Subtraction(Number(5), Number(3)) 6 | three_plus_six = Sum(Number(3), Number(6)) 7 | 8 | complex_expression = Multiplication(five_minus_three, three_plus_six) 9 | 10 | final_expression = Division(complex_expression, Number(2)) 11 | 12 | print(f'((5 - 3) * (3 + 6)) / 2 = {final_expression.evaluate()}') 13 | -------------------------------------------------------------------------------- /Behavioral/Iterator/README.md: -------------------------------------------------------------------------------- 1 | # Iterator 2 | 3 | Iterator pattern is one of the behavioral pattern and it’s used to provide a standard way to traverse through a group of Objects. -------------------------------------------------------------------------------- /Behavioral/Iterator/java/CollectionOfDouble.java: -------------------------------------------------------------------------------- 1 | interface CollectionOfDouble { 2 | public void add(double x); 3 | public int size(); 4 | public IteratorOfDouble iterator(); 5 | } -------------------------------------------------------------------------------- /Behavioral/Iterator/java/IteratorDemo.java: -------------------------------------------------------------------------------- 1 | public class IteratorDemo { 2 | 3 | public static void main(String[] args) { 4 | double[] values = { 1.0, 5.5, 3.2, 2.3, 9.8 }; 5 | CollectionOfDouble colecao = new ListOfDouble(10); 6 | for (double d : values) { 7 | colecao.add(d); 8 | } 9 | printList(colecao); 10 | } 11 | 12 | public static void printList(CollectionOfDouble collection) { 13 | System.out.print("Elements: "); 14 | IteratorOfDouble iterator = collection.iterator(); 15 | while (iterator.hasNext()) { 16 | System.out.print(iterator.next() + " "); 17 | } 18 | System.out.println(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Behavioral/Iterator/java/IteratorGenerics.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Simple iterators methods which can iterate over generic data. 3 | * 4 | * @author ByWaleed 5 | * @version October 2019 6 | * */ 7 | 8 | public class IteratorGenerics { 9 | 10 | public void forLoop(T[] array) { 11 | for (int i = 0; i < array.length(); i++) { 12 | T val = array[i]; 13 | System.out.println(val + " "); 14 | } 15 | } 16 | 17 | public void forEachLoop(T[] array) { 18 | for (T val : array) { 19 | System.out.println(val + " "); 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Behavioral/Iterator/java/IteratorOfDouble.java: -------------------------------------------------------------------------------- 1 | 2 | public interface IteratorOfDouble { 3 | public double next(); 4 | public boolean hasNext(); 5 | } 6 | -------------------------------------------------------------------------------- /Behavioral/Iterator/java/ListOfDouble.java: -------------------------------------------------------------------------------- 1 | 2 | public class ListOfDouble implements CollectionOfDouble { 3 | private double[] elements; 4 | private int pointer; // point the first empty slot in the array 5 | 6 | public ListOfDouble(int size) { 7 | elements = new double[size]; 8 | pointer = 0; 9 | } 10 | 11 | public void add(double x) { 12 | elements[pointer++] = x; 13 | } 14 | 15 | public int size() { 16 | return pointer; 17 | } 18 | 19 | public double getElement(int index) { 20 | return elements[index]; 21 | } 22 | 23 | public IteratorOfDouble iterator() { 24 | return new ListOfDoubleIterator(this); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Behavioral/Iterator/java/ListOfDoubleIterator.java: -------------------------------------------------------------------------------- 1 | 2 | public class ListOfDoubleIterator implements IteratorOfDouble { 3 | private ListOfDouble list; 4 | private int index; 5 | 6 | public ListOfDoubleIterator(ListOfDouble list) { 7 | this.list = list; 8 | index=0; 9 | } 10 | 11 | public double next() { 12 | return list.getElement(index++); 13 | } 14 | 15 | public boolean hasNext() { 16 | return index < list.size(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Behavioral/Mediator/javascript/mediator.js: -------------------------------------------------------------------------------- 1 | class Mediator { 2 | send(user, message) { 3 | console.log(`${user} said ${message}`); 4 | } 5 | } 6 | 7 | class Animal { 8 | constructor(name, mediator) { 9 | this.name = name; 10 | this.mediator = mediator; 11 | } 12 | 13 | send(message) { 14 | this.mediator.send(this.name, message); 15 | } 16 | } 17 | 18 | const mediator = new Mediator(); 19 | 20 | const dog = new Animal('Dog', mediator); 21 | const cat = new Animal('Cat', mediator); 22 | 23 | dog.send('hi cat'); 24 | cat.send('hi dog'); 25 | -------------------------------------------------------------------------------- /Behavioral/Mediator/python/mediator.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | class User(object): 4 | def __init__(self, name, mediator): 5 | self.name = name 6 | self.mediator = mediator 7 | 8 | def send(self, message): 9 | mediator.ping(self.name, message) 10 | 11 | 12 | class Mediator(object): 13 | def ping(self, name, message): 14 | print("User: {}: {}".format(name, message)) 15 | 16 | if __name__ == "__main__": 17 | mediator = Mediator() 18 | 19 | tom = User("Tom", mediator) 20 | mark = User("Mark", mediator) 21 | 22 | tom.send("What's up man?") 23 | mark.send("Not much!") 24 | 25 | -------------------------------------------------------------------------------- /Behavioral/Memento/Java/FileWriterCaretaker.java: -------------------------------------------------------------------------------- 1 | public class FileWriterCaretaker { 2 | 3 | private Object obj; 4 | 5 | public void save(FileWriterUtil fileWriter){ 6 | this.obj=fileWriter.save(); 7 | } 8 | 9 | public void undo(FileWriterUtil fileWriter){ 10 | fileWriter.undoToLastSave(obj); 11 | } 12 | } -------------------------------------------------------------------------------- /Behavioral/Memento/Java/FileWriterClient.java: -------------------------------------------------------------------------------- 1 | public class FileWriterClient { 2 | 3 | public static void main(String[] args) { 4 | 5 | FileWriterCaretaker caretaker = new FileWriterCaretaker(); 6 | 7 | FileWriterUtil fileWriter = new FileWriterUtil("data.txt"); 8 | fileWriter.write("First Set of Data\n"); 9 | System.out.println(fileWriter+"\n\n"); 10 | 11 | // lets save the file 12 | caretaker.save(fileWriter); 13 | //now write something else 14 | fileWriter.write("Second Set of Data\n"); 15 | 16 | //checking file contents 17 | System.out.println(fileWriter+"\n\n"); 18 | 19 | //lets undo to last save 20 | caretaker.undo(fileWriter); 21 | 22 | //checking file content again 23 | System.out.println(fileWriter+"\n\n"); 24 | 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Behavioral/Memento/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Behavioral/Memento/README.md -------------------------------------------------------------------------------- /Behavioral/Memento/ruby/caretaker.rb: -------------------------------------------------------------------------------- 1 | require './memento' 2 | 3 | class CareTaker 4 | attr_reader :mementos 5 | 6 | def initialize 7 | @mementos = [] 8 | end 9 | 10 | def add(memento) 11 | mementos.push(memento) 12 | end 13 | 14 | def [](index) 15 | mementos[index] 16 | end 17 | 18 | end 19 | -------------------------------------------------------------------------------- /Behavioral/Memento/ruby/memento.rb: -------------------------------------------------------------------------------- 1 | 2 | class Memento 3 | 4 | attr_reader :state 5 | 6 | def initialize(state) 7 | @state = state 8 | end 9 | 10 | end 11 | -------------------------------------------------------------------------------- /Behavioral/Memento/ruby/originator.rb: -------------------------------------------------------------------------------- 1 | require './memento' 2 | 3 | class Originator 4 | attr_accessor :state 5 | 6 | def save 7 | Memento.new(state) 8 | end 9 | 10 | def restore(memento) 11 | state= memento.state 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /Behavioral/NullObject/CSharp/Bicycle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace NullObjectPattern 8 | { 9 | public class Bicycle : Vehicle 10 | { 11 | public override void SetEngine(string name, int power) 12 | { 13 | Engine = Engine.NoEngine(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Behavioral/NullObject/CSharp/Car.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace NullObjectPattern 8 | { 9 | public class Car : Vehicle 10 | { 11 | public override void SetEngine(string name, int power) 12 | { 13 | Engine = new Engine(name, power); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Behavioral/NullObject/CSharp/Engine.cs: -------------------------------------------------------------------------------- 1 | namespace NullObjectPattern 2 | { 3 | public class Engine 4 | { 5 | public string Type { get; set; } 6 | public int Power { get; set; } 7 | 8 | public Engine(string type, int power) 9 | { 10 | Type = type; 11 | Power = power; 12 | } 13 | 14 | public override string ToString() 15 | { 16 | return Power == -1 ? "No engine here :(" : $"{Type} with power of: {Power}"; 17 | } 18 | 19 | public static Engine NoEngine() 20 | { 21 | return new Engine("NoEngine", -1); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Behavioral/NullObject/CSharp/Motorcycle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace NullObjectPattern 8 | { 9 | public class Motorcycle : Vehicle 10 | { 11 | public override void SetEngine(string name, int power) 12 | { 13 | Engine = new Engine(name, power); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Behavioral/NullObject/CSharp/Vehicle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace NullObjectPattern 8 | { 9 | public abstract class Vehicle 10 | { 11 | public void Start() 12 | { 13 | Console.WriteLine($"{GetType().Name} Wruuuuum"); 14 | } 15 | public Engine Engine { get; set; } 16 | 17 | public abstract void SetEngine(string name, int power); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Behavioral/NullObject/Java/AbstractDrink.java: -------------------------------------------------------------------------------- 1 | public abstract class AbstractDrink { 2 | protected String name; 3 | protected int price; 4 | 5 | public abstract boolean isNull(); 6 | 7 | public abstract String getName(); 8 | 9 | public abstract int getPrice(); 10 | } -------------------------------------------------------------------------------- /Behavioral/NullObject/Java/DrinkManager.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class DrinkManager { 5 | public static final Map data = new HashMap(){{ 6 | put("Coke", 10); 7 | put("Tea", 5); 8 | put("Coffee", 3); 9 | }}; 10 | 11 | public static AbstractDrink getDrink(String drinkName){ 12 | return data.containsKey(drinkName) ? new RealDrink(drinkName, data.get(drinkName)) : new NullDrink(); 13 | } 14 | } -------------------------------------------------------------------------------- /Behavioral/NullObject/Java/NullDrink.java: -------------------------------------------------------------------------------- 1 | public class NullDrink extends AbstractDrink { 2 | @Override 3 | public String getName() { 4 | return "Drink not found."; 5 | } 6 | 7 | @Override 8 | public int getPrice() { 9 | return 0; 10 | } 11 | 12 | @Override 13 | public boolean isNull() { 14 | return true; 15 | } 16 | } -------------------------------------------------------------------------------- /Behavioral/NullObject/Java/NullObjectPatternDemo.java: -------------------------------------------------------------------------------- 1 | public class NullObjectPatternDemo { 2 | public static void main(String[] args) { 3 | String[] drinkList = {"Cocacola", "Tea", "Dasani", "Juice", "Coke"}; 4 | int bill = 0; 5 | System.out.println("Checking out items:"); 6 | for (String drinkName : drinkList) { 7 | AbstractDrink drink = DrinkManager.getDrink(drinkName); 8 | System.out.println("- " + drinkName + ": " + (drink.isNull() ? drink.getName() : drink.getPrice() + "$.")); 9 | bill += drink.getPrice(); 10 | } 11 | 12 | System.out.println("Total bill: " + bill + "$."); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Behavioral/NullObject/Java/RealDrink.java: -------------------------------------------------------------------------------- 1 | public class RealDrink extends AbstractDrink { 2 | public RealDrink(String name, int price) { 3 | this.name = name; 4 | this.price = price; 5 | } 6 | 7 | @Override 8 | public String getName() { 9 | return name; 10 | } 11 | 12 | @Override 13 | public int getPrice() { 14 | return price; 15 | } 16 | 17 | @Override 18 | public boolean isNull() { 19 | return false; 20 | } 21 | } -------------------------------------------------------------------------------- /Behavioral/NullObject/README.md: -------------------------------------------------------------------------------- 1 | # Null Object Pattern 2 | 3 | > Reflect a do nothing relationship. 4 | 5 | This pattern is commonly used to provide behavior in case data is not available. In most object-oriented languages, such as Java or C#, references may be null. These references need to be checked to ensure they are not null before invoking any methods, because methods typically cannot be invoked on null references. 6 | 7 | For more information, Wikipedia provides a great overview of the pattern: [Wikipedia Article](https://en.wikipedia.org/wiki/Null_object_pattern) -------------------------------------------------------------------------------- /Behavioral/Observer/Cpp/GraphObserver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Observer.h" 3 | #include "Group.h" 4 | 5 | class GraphObserver: public Observer { 6 | public: 7 | GraphObserver(); 8 | GraphObserver(Group *); 9 | void update(); 10 | }; 11 | -------------------------------------------------------------------------------- /Behavioral/Observer/Cpp/Group.cpp: -------------------------------------------------------------------------------- 1 | #include "Group.h" 2 | 3 | Group::Group (int x, int y) { 4 | this->canHombres= x; 5 | this->canMujeres= y; 6 | } 7 | 8 | void Group::attach(Observer *obs) { 9 | v.push_back(obs); 10 | } 11 | 12 | void Group::setQtyMen(int val) { 13 | canHombres = val; 14 | notify(); 15 | } 16 | 17 | void Group::setQtyWomen(int val) { 18 | canMujeres = val; 19 | notify(); 20 | } 21 | 22 | int Group::getQtyWomen() { 23 | return canMujeres; 24 | } 25 | 26 | int Group::getQtyMen() { 27 | return canHombres; 28 | } 29 | 30 | void Group::notify() { 31 | if (v.size() > 0){ 32 | for (int i = 0; i < v.size(); i++){ 33 | v[i]->update(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Behavioral/Observer/Cpp/Group.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | using namespace std; 4 | #include "Observer.h"; 5 | #include ; 6 | 7 | class Observer;// para evitar el problema de referencia circular 8 | class Group { 9 | int canHombres; 10 | int canMujeres; 11 | vector v; 12 | public: 13 | Group (int , int) ; 14 | void attach(Observer *) ; 15 | void setQtyMen(int ) ; 16 | void setQtyWomen(int ) ; 17 | int getQtyMen(); 18 | int getQtyWomen(); 19 | void notify() ; 20 | }; 21 | -------------------------------------------------------------------------------- /Behavioral/Observer/Cpp/Observer .cpp: -------------------------------------------------------------------------------- 1 | #include "Observer.h"; 2 | 3 | Observer::Observer(Group* x) { 4 | subject =x; 5 | subject->attach(this); 6 | } 7 | 8 | Group * Observer::getGroup() { return subject; } 9 | -------------------------------------------------------------------------------- /Behavioral/Observer/Cpp/Observer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Group.h"; 3 | 4 | class Group;// para evitar el problema de rerencia circular 5 | 6 | class Observer { 7 | protected: 8 | Group* subject; 9 | public: 10 | Observer(Group*); 11 | virtual void update() = 0; 12 | Group * getGroup(); 13 | }; 14 | -------------------------------------------------------------------------------- /Behavioral/Observer/Cpp/TableObserver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Observer.h" 3 | #include "Group.h" 4 | 5 | class TableObserver: public Observer { 6 | public: 7 | TableObserver(); 8 | TableObserver(Group *); 9 | void update(); 10 | }; 11 | -------------------------------------------------------------------------------- /Behavioral/Observer/Cpp/main.cpp: -------------------------------------------------------------------------------- 1 | #include "GraphObserver.h" 2 | #include "TableObserver.h" 3 | 4 | int main() { 5 | Group* g1 = new Group(20, 5); 6 | GraphObserver* myGraph = new GraphObserver(g1); 7 | TableObserver* myTable = new TableObserver(g1); 8 | myGraph->update(); 9 | myTable->update(); 10 | 11 | cout << "Press a key to set the quantity of women to 20" << endl; 12 | cin.get(); 13 | 14 | g1->setQtyWomen(20); 15 | cout << endl << endl; 16 | 17 | cout << "Press a key to set the quantity of men to 10" << endl; 18 | cin.get(); 19 | 20 | cout << endl << endl; 21 | g1->setQtyMen(10); 22 | 23 | cin.get(); 24 | } 25 | -------------------------------------------------------------------------------- /Behavioral/Observer/Kotlin/observer.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | import java.util.Random 3 | 4 | class Printer : Observer{ 5 | override fun update(p0: Observable?, p1: Any?) { 6 | val value = p1 as Int 7 | println(value) 8 | } 9 | 10 | } 11 | 12 | class RandomGenerator : Observable() { 13 | 14 | fun newRandom(){ 15 | setChanged() 16 | notifyObservers(Random().nextInt()) 17 | } 18 | } 19 | 20 | fun main (args : Array){ 21 | val p = Printer() 22 | val r = RandomGenerator() 23 | 24 | r.addObserver(p) 25 | r.newRandom() 26 | r.newRandom() 27 | r.newRandom() 28 | 29 | 30 | } -------------------------------------------------------------------------------- /Behavioral/Observer/README.md: -------------------------------------------------------------------------------- 1 | # Observer Pattern 2 | 3 | > Automatically notify objects of changes to the application state. 4 | 5 | This pattern is commonly used in event-driven software to ensure that objects are aware of the application state. In this pattern, when the _subject_ class changes state, it automatically notifies all registered _observer_ classes of this change. This allows for the application to respond and be reconfigured based on state changes at runtime. 6 | 7 | For more information, Wikipedia provides a great overview of the pattern: [Wikipedia Article](https://en.wikipedia.org/wiki/Observer_pattern) -------------------------------------------------------------------------------- /Behavioral/Observer/java/ObserverDesignPattern.java: -------------------------------------------------------------------------------- 1 | public class ObserverDesignPattern { 2 | public static void main(String[] args) { 3 | //Create a new subject 4 | WeatherSubject weatherSubject = new WeatherSubject(); 5 | 6 | //Register the observers 7 | weatherSubject.registerObserver(new CitizenObserver()); 8 | weatherSubject.registerObserver(new RestaurantObserver()); 9 | 10 | //Change the current weather, notifying the appropriate observers 11 | for (WeatherType weatherType : WeatherType.values()) { 12 | weatherSubject.setCurrentWeatherType(weatherType); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Behavioral/Observer/java/WeatherObserver.java: -------------------------------------------------------------------------------- 1 | public interface WeatherObserver { 2 | void notify(WeatherType weatherType); 3 | } 4 | -------------------------------------------------------------------------------- /Behavioral/Observer/java/WeatherType.java: -------------------------------------------------------------------------------- 1 | public enum WeatherType { 2 | SUNNY, RAINY, WINDY, COLD 3 | } 4 | -------------------------------------------------------------------------------- /Behavioral/State/README.md: -------------------------------------------------------------------------------- 1 | # State 2 | 3 | The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. 4 | This pattern is close to the concept of finite-state machines. 5 | The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface. 6 | 7 | 8 | ![callback visualization](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/State_Design_Pattern_UML_Class_Diagram.svg/600px-State_Design_Pattern_UML_Class_Diagram.svg.png) 9 | 10 | For more information, Wikipedia provides a great overview of the pattern: [Wikipedia Article](https://en.wikipedia.org/wiki/State_pattern) 11 | -------------------------------------------------------------------------------- /Behavioral/State/java/CalculateState.java: -------------------------------------------------------------------------------- 1 | public class CalculateState implements CashierState{ 2 | @Override 3 | public void cashierAction(StateContext stateContext) { 4 | // TODO Auto-generated method stub 5 | System.out.println("Cashier is calculating your bill"); 6 | stateContext.setState(this); 7 | } 8 | 9 | public String toString() { 10 | return "CollectMoneyState"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Behavioral/State/java/CashierState.java: -------------------------------------------------------------------------------- 1 | 2 | public interface CashierState { 3 | public void cashierAction(StateContext stateContext); 4 | } 5 | -------------------------------------------------------------------------------- /Behavioral/State/java/CollectMoneyState.java: -------------------------------------------------------------------------------- 1 | 2 | public class CollectMoneyState implements CashierState{ 3 | @Override 4 | public void cashierAction(StateContext stateContext) { 5 | System.out.println("Cashier is collecting your money"); 6 | stateContext.setState(this); 7 | } 8 | 9 | public String toString() { 10 | return "CollectMoneyState"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Behavioral/State/java/FinishState.java: -------------------------------------------------------------------------------- 1 | 2 | public class FinishState implements CashierState{ 3 | @Override 4 | public void cashierAction(StateContext stateContext) { 5 | System.out.println("Cashier is done with your shopping cart"); 6 | stateContext.setState(this); 7 | } 8 | 9 | public String toString() { 10 | return "FinishState"; 11 | } 12 | } -------------------------------------------------------------------------------- /Behavioral/State/java/README.md: -------------------------------------------------------------------------------- 1 | # State Pattern 2 | 3 | > Automatically change behaviors depending on the internal states. 4 | 5 | This pattern is commonly used in state machines to encapsulate various behaviors based on its internal state. In this pattern, when the state changes, it automatically behaves depending on the state. This allows new states to be added independent from the existing state behaviors. 6 | 7 | For more information, Wikipedia provides a great overview of the pattern: [Wikipedia Article](https://en.wikipedia.org/wiki/State_pattern) -------------------------------------------------------------------------------- /Behavioral/State/java/ScanGoodsState.java: -------------------------------------------------------------------------------- 1 | 2 | public class ScanGoodsState implements CashierState{ 3 | @Override 4 | public void cashierAction(StateContext stateContext) { 5 | System.out.println("Cashier is scanning your goods"); 6 | stateContext.setState(this); 7 | } 8 | 9 | public String toString() { 10 | return "ScanGoodsState"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Behavioral/State/java/StartState.java: -------------------------------------------------------------------------------- 1 | 2 | public class StartState implements CashierState{ 3 | @Override 4 | public void cashierAction(StateContext stateContext) { 5 | System.out.println("Cashier is starting with your shopping cart"); 6 | stateContext.setState(this); 7 | } 8 | 9 | public String toString() { 10 | return "StartState"; 11 | } 12 | } -------------------------------------------------------------------------------- /Behavioral/State/java/StateContext.java: -------------------------------------------------------------------------------- 1 | 2 | public class StateContext { 3 | private CashierState cashierstate; 4 | 5 | public StateContext(){ 6 | cashierstate = null; 7 | } 8 | 9 | public void setState(CashierState cashierstate){ 10 | this.cashierstate = cashierstate; 11 | } 12 | 13 | public CashierState getState(){ 14 | return cashierstate; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Behavioral/Strategy/C#/Bus.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace StrategyPattern 4 | { 5 | class Bus : Strategy 6 | { 7 | public void Execute() 8 | { 9 | Console.WriteLine("Use the bus"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Behavioral/Strategy/C#/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace StrategyPattern 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | PublicTransport publicTransport = new PublicTransport(new Train()); 10 | publicTransport.ExecuteStrategy(); 11 | 12 | //Now we can easily change this objects' strategy to another 13 | publicTransport.Strategy = new Bus(); 14 | publicTransport.ExecuteStrategy(); 15 | 16 | Console.ReadLine(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Behavioral/Strategy/C#/PublicTransport.cs: -------------------------------------------------------------------------------- 1 | namespace StrategyPattern 2 | { 3 | class PublicTransport 4 | { 5 | public Strategy Strategy { get; set; } 6 | 7 | public PublicTransport(Strategy strategy) 8 | { 9 | this.Strategy = strategy; 10 | } 11 | 12 | public void ExecuteStrategy() 13 | { 14 | Strategy.Execute(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Behavioral/Strategy/C#/Strategy.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace StrategyPattern 4 | { 5 | interface Strategy 6 | { 7 | void Execute(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Behavioral/Strategy/C#/Train.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace StrategyPattern 4 | { 5 | class Train : Strategy 6 | { 7 | public void Execute() 8 | { 9 | Console.WriteLine("Use the train"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Behavioral/Strategy/README.md: -------------------------------------------------------------------------------- 1 | # Strategy Pattern 2 | 3 | > Defer the selection of algorithms until runtime. 4 | 5 | This pattern is commonly used to promote flexible and reusable code by deferring the selection of algorithms to runtime. Rather than implementing algorithms directly within a class, using an interface with multiple implementations leads to the ability to quickly change implementation details as requirements change and make decisions about algorithm usage based on application state. 6 | 7 | For more information, Wikipedia provides a great overview of the pattern: [Wikipedia Article](https://en.wikipedia.org/wiki/Strategy_pattern) -------------------------------------------------------------------------------- /Behavioral/Strategy/cpp/BillingStrategy.hpp: -------------------------------------------------------------------------------- 1 | #ifndef BILLING_STRATEGY 2 | #define BILLING_STRATEGY 3 | 4 | #include 5 | #include "Product.hpp" 6 | 7 | class BillingStrategy 8 | { 9 | public: 10 | virtual ~BillingStrategy() = default; 11 | virtual double getTotal(std::list products) = 0; 12 | }; 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /Behavioral/Strategy/cpp/Demo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "Product.hpp" 6 | #include "BillingStrategy.hpp" 7 | #include "DiscountStrategy.hpp" 8 | #include "NormalStrategy.hpp" 9 | 10 | int main(int argc, char **argv) 11 | { 12 | Product pa("Product A", 20); 13 | Product pb("Product B", 10); 14 | 15 | std::list products; 16 | products.push_front(pa); 17 | products.push_front(pb); 18 | 19 | BillingStrategy *strategy = new NormalStrategy(); 20 | std::cout<<"Normal: "<getTotal(products)<getTotal(products)< products) override 14 | { 15 | double sum = 0; 16 | for (Product &product:products) 17 | sum += product.price; 18 | return sum * (1-percentage/100); 19 | } 20 | }; 21 | #endif 22 | -------------------------------------------------------------------------------- /Behavioral/Strategy/cpp/NormalStrategy.hpp: -------------------------------------------------------------------------------- 1 | #ifndef NORMAL 2 | #define NORMAL 3 | 4 | #include "BillingStrategy.hpp" 5 | 6 | class NormalStrategy : public BillingStrategy 7 | { 8 | public: 9 | double getTotal(std::list products) override 10 | { 11 | double sum = 0; 12 | for (Product &product:products) 13 | sum += product.price; 14 | return sum; 15 | } 16 | }; 17 | #endif 18 | -------------------------------------------------------------------------------- /Behavioral/Strategy/cpp/Product.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PRODUCT 2 | #define PRODUCT 3 | 4 | #include 5 | 6 | class Product 7 | { 8 | public: 9 | std::string name; 10 | double price; 11 | 12 | Product(const std::string &name, double price) 13 | { 14 | this->name = name; 15 | this->price = price; 16 | } 17 | }; 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/Aluguel.java: -------------------------------------------------------------------------------- 1 | 2 | public class Aluguel { 3 | private Fita fita; 4 | private int diasAlugada; 5 | 6 | public Aluguel(Fita fita, int diasAlugada) { 7 | this.fita = fita; 8 | this.diasAlugada = diasAlugada; 9 | } 10 | public Fita getFita() { 11 | return fita; 12 | } 13 | public int getDiasAlugada() { 14 | return diasAlugada; 15 | } 16 | 17 | public double getValor() { 18 | return fita.getValor(diasAlugada); 19 | } 20 | 21 | public String getTituloFita() { 22 | return fita.getTitulo(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/BillingStrategy.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public interface BillingStrategy { 4 | double getTotal(List productList); 5 | } 6 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/DiscountStrategy.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public class DiscountStrategy implements BillingStrategy { 4 | private double discountPercentage; 5 | 6 | public DiscountStrategy(double discountPercentage) { 7 | this.discountPercentage = discountPercentage; 8 | } 9 | 10 | @Override 11 | public double getTotal(List productList) { 12 | return productList.stream().mapToDouble(Product::getPrice).sum() * (1 - discountPercentage / 100) ; 13 | } 14 | } -------------------------------------------------------------------------------- /Behavioral/Strategy/java/Fita.java: -------------------------------------------------------------------------------- 1 | 2 | public class Fita { 3 | private TipoFita tipo; 4 | private String titulo; 5 | public Fita(String titulo, TipoFita tipo) { 6 | this.titulo = titulo; 7 | this.tipo = tipo; 8 | } 9 | 10 | public String getTitulo() { 11 | return titulo; 12 | } 13 | 14 | public double getValor(int diasAlugada) { 15 | return this.tipo.calculaPrecoFita(diasAlugada); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/FitaInfantil.java: -------------------------------------------------------------------------------- 1 | public class FitaInfantil implements TipoFita{ 2 | @Override 3 | public double calculaPrecoFita(int diasAlugada) { 4 | double valorCorrente = 1.5; 5 | if(diasAlugada > 3) { 6 | valorCorrente += (diasAlugada - 3) * 1.5; 7 | } 8 | return valorCorrente; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/FitaLancamento.java: -------------------------------------------------------------------------------- 1 | public class FitaLancamento implements TipoFita{ 2 | @Override 3 | public double calculaPrecoFita(int diasAlugada) { 4 | return diasAlugada * 3; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/FitaNormal.java: -------------------------------------------------------------------------------- 1 | public class FitaNormal implements TipoFita { 2 | @Override 3 | public double calculaPrecoFita(int diasAlugada) { 4 | double valorCorrente = 2; 5 | if(diasAlugada > 2) { 6 | valorCorrente += (diasAlugada - 2) * 1.5; 7 | } 8 | return valorCorrente; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/NormalStrategy.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public class NormalStrategy implements BillingStrategy { 4 | @Override 5 | public double getTotal(List productList) { 6 | return productList.stream().mapToDouble(Product::getPrice).sum(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/Product.java: -------------------------------------------------------------------------------- 1 | public class Product { 2 | private String name; 3 | private double price; 4 | 5 | public Product(String name, double price) { 6 | this.name = name; 7 | this.price = price; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public void setName(String name) { 15 | this.name = name; 16 | } 17 | 18 | public double getPrice() { 19 | return price; 20 | } 21 | 22 | public void setPrice(double price) { 23 | this.price = price; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/StrategyDemo.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | 4 | public class StrategyDemo { 5 | public static void main(String[] args) { 6 | Product productA = new Product("Product A", 20); 7 | Product productB = new Product("Product B", 10); 8 | List productList = Arrays.asList(productA, productB); 9 | 10 | BillingStrategy normalStrategy = new NormalStrategy(); 11 | System.out.println(normalStrategy.getTotal(productList)); 12 | 13 | BillingStrategy discountStrategy = new DiscountStrategy(10); 14 | System.out.println(discountStrategy.getTotal(productList)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/TipoFita.java: -------------------------------------------------------------------------------- 1 | public interface TipoFita { 2 | public double calculaPrecoFita(int diasAlugada); 3 | } 4 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/basket/app/strategies/NormalPricesStrategy.java: -------------------------------------------------------------------------------- 1 | package app.strategies; 2 | 3 | import app.Product; 4 | 5 | import java.math.BigDecimal; 6 | import java.util.List; 7 | 8 | public class NormalPricesStrategy implements PriceCounterStrategy { 9 | 10 | 11 | @Override 12 | public BigDecimal productDiscount(Product product) { 13 | return BigDecimal.ZERO; 14 | } 15 | 16 | @Override 17 | public BigDecimal discount(List products, BigDecimal basketPrice) { 18 | return BigDecimal.ZERO; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/basket/app/strategies/PriceCounterStrategy.java: -------------------------------------------------------------------------------- 1 | package app.strategies; 2 | 3 | import app.Product; 4 | 5 | import java.math.BigDecimal; 6 | import java.util.List; 7 | 8 | public interface PriceCounterStrategy { 9 | 10 | BigDecimal productDiscount(Product product); 11 | 12 | BigDecimal discount(List products, BigDecimal basketPrice); 13 | } 14 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/medievalstrategy/ArmyKeyAsset.java: -------------------------------------------------------------------------------- 1 | package medievalstrategy; 2 | 3 | public enum ArmyKeyAsset { 4 | 5 | FURTIVITY, 6 | STRENGTH, 7 | NETWORKING 8 | } 9 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/medievalstrategy/WarLord.java: -------------------------------------------------------------------------------- 1 | package medievalstrategy; 2 | 3 | public class WarLord { 4 | 5 | private WarStrategy strategy; 6 | 7 | public WarLord() { 8 | } 9 | 10 | public void setStrategy(WarStrategy strategy) { 11 | this.strategy = strategy; 12 | } 13 | 14 | public void besiegeTheCity() { 15 | System.out.println(" ►►►►►►► " + this.strategy.attack()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/medievalstrategy/WarStrategy.java: -------------------------------------------------------------------------------- 1 | package medievalstrategy; 2 | 3 | public interface WarStrategy { 4 | String attack(); 5 | } 6 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/medievalstrategy/strategies/CallTheTanks.java: -------------------------------------------------------------------------------- 1 | package medievalstrategy.strategies; 2 | 3 | import medievalstrategy.WarStrategy; 4 | 5 | public class CallTheTanks implements WarStrategy { 6 | @Override 7 | public String attack() { 8 | return "🚀 Besiege the gate by calling the tanks"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/medievalstrategy/strategies/DestroyTheGate.java: -------------------------------------------------------------------------------- 1 | package medievalstrategy.strategies; 2 | 3 | import medievalstrategy.WarStrategy; 4 | 5 | public class DestroyTheGate implements WarStrategy { 6 | @Override 7 | public String attack() { 8 | return "👑 Besiege the gate by destroying the gate"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/medievalstrategy/strategies/UseTheSecretPassage.java: -------------------------------------------------------------------------------- 1 | package medievalstrategy.strategies; 2 | 3 | import medievalstrategy.WarStrategy; 4 | 5 | public class UseTheSecretPassage implements WarStrategy { 6 | @Override 7 | public String attack() { 8 | return "👺 Besiege the gate by using the secret passage"; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/strategy_arithmetical_operations/images/strategy_pattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Behavioral/Strategy/java/strategy_arithmetical_operations/images/strategy_pattern.png -------------------------------------------------------------------------------- /Behavioral/Strategy/java/strategy_arithmetical_operations/src/main/java/com/mycompany/strategy_arithmetical_operations/CalculatorContext.java: -------------------------------------------------------------------------------- 1 | package com.mycompany.strategy_arithmetical_operations; 2 | 3 | // Context: Represents the arithmetic calculator 4 | public class CalculatorContext { 5 | 6 | private Strategy strategy; 7 | 8 | // Set the strategy dynamically 9 | public void setStrategy(Strategy strategy) { 10 | this.strategy = strategy; 11 | } 12 | 13 | // Execute the selected strategy 14 | public int executeStrategy(int a, int b) { 15 | if (strategy == null) { 16 | throw new IllegalStateException("Strategy not set."); 17 | } 18 | return strategy.execute(a, b); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/strategy_arithmetical_operations/src/main/java/com/mycompany/strategy_arithmetical_operations/ConcreteStrategyAdd.java: -------------------------------------------------------------------------------- 1 | package com.mycompany.strategy_arithmetical_operations; 2 | 3 | // Concrete Strategy for Addition 4 | public class ConcreteStrategyAdd implements Strategy { 5 | 6 | @Override 7 | public int execute(int a, int b) { 8 | return a + b; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/strategy_arithmetical_operations/src/main/java/com/mycompany/strategy_arithmetical_operations/ConcreteStrategyMultiply.java: -------------------------------------------------------------------------------- 1 | package com.mycompany.strategy_arithmetical_operations; 2 | 3 | // Concrete Strategy for Multiplication 4 | public class ConcreteStrategyMultiply implements Strategy { 5 | 6 | @Override 7 | public int execute(int a, int b) { 8 | return a * b; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/strategy_arithmetical_operations/src/main/java/com/mycompany/strategy_arithmetical_operations/ConcreteStrategySubstract.java: -------------------------------------------------------------------------------- 1 | package com.mycompany.strategy_arithmetical_operations; 2 | 3 | // Concrete Strategy for Substraction 4 | public class ConcreteStrategySubstract implements Strategy { 5 | 6 | @Override 7 | public int execute(int a, int b) { 8 | return a - b; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/strategy_arithmetical_operations/src/main/java/com/mycompany/strategy_arithmetical_operations/Strategy.java: -------------------------------------------------------------------------------- 1 | package com.mycompany.strategy_arithmetical_operations; 2 | 3 | // Strategy Interface: Defines the common behavior for all strategies 4 | public interface Strategy { 5 | 6 | int execute(int a, int b); 7 | } 8 | -------------------------------------------------------------------------------- /Behavioral/Strategy/java/strategy_arithmetical_operations/src/main/java/com/mycompany/strategy_arithmetical_operations/Strategy_arithmetical_operations.java: -------------------------------------------------------------------------------- 1 | package com.mycompany.strategy_arithmetical_operations; 2 | 3 | public class Strategy_arithmetical_operations { 4 | 5 | public static void main(String[] args) { 6 | 7 | CalculatorClient.calculatorClient(); 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Behavioral/Strategy/javascript/administration.js: -------------------------------------------------------------------------------- 1 | const Administration = function() { 2 | this.print = role => { 3 | return ` 4 | ${role.toUpperCase()} 5 | * Diary management and arranging appointments, booking meeting rooms and conference facilities 6 | * Data entry (sales figures, property listings etc.) 7 | * General office management such as ordering stationary`; 8 | }; 9 | }; 10 | 11 | module.exports = Administration; 12 | -------------------------------------------------------------------------------- /Behavioral/Strategy/javascript/developer.js: -------------------------------------------------------------------------------- 1 | const Developer = function() { 2 | this.print = role => { 3 | return ` 4 | ${role.toUpperCase()} 5 | * Producing clean, efficient code based on specifications 6 | * Testing and deploying programs and systems 7 | * Fixing and improving existing software`; 8 | }; 9 | }; 10 | 11 | module.exports = Developer; 12 | -------------------------------------------------------------------------------- /Behavioral/Strategy/javascript/employee.js: -------------------------------------------------------------------------------- 1 | const Employee = function() { 2 | this.roleDescription; 3 | }; 4 | 5 | Employee.prototype = { 6 | setStrategy: roleDescription => { 7 | this.roleDescription = roleDescription; 8 | }, 9 | 10 | print: role => { 11 | return this.roleDescription.print(role); 12 | } 13 | }; 14 | 15 | module.exports = Employee; 16 | -------------------------------------------------------------------------------- /Behavioral/Strategy/javascript/index.js: -------------------------------------------------------------------------------- 1 | const DeveloperStrategy = require("./developer"); 2 | const AdministrationStrategy = require("./administration"); 3 | const EmployeeContext = require("./employee"); 4 | 5 | const dev = new DeveloperStrategy(); 6 | const adm = new AdministrationStrategy(); 7 | 8 | const emp = new EmployeeContext(); 9 | 10 | emp.setStrategy(dev); 11 | let out = emp.print("developer"); 12 | console.log(out); 13 | 14 | emp.setStrategy(adm); 15 | out = emp.print("administration"); 16 | console.log(out); 17 | -------------------------------------------------------------------------------- /Behavioral/Strategy/kotlin/FunctionalStrategy.kt: -------------------------------------------------------------------------------- 1 | class Product(val name: String, val price: Double) 2 | 3 | inline fun getTotal(productList: List, strategy: (price: Double) -> Double): Double { 4 | return productList 5 | .map { strategy(it.price) } 6 | .sum() 7 | } 8 | 9 | fun normalStrategy(price: Double) = price 10 | 11 | fun main(args: Array) { 12 | val productA = Product("Product A", 10.0) 13 | val productB = Product("Product B", 25.6) 14 | 15 | val products = listOf(productA, productB) 16 | 17 | println(getTotal(products, ::normalStrategy)) 18 | 19 | val discount = 25 20 | println(getTotal(products) { 21 | it - it * discount / 100 22 | }) 23 | } 24 | -------------------------------------------------------------------------------- /Behavioral/Strategy/python/sorting_strategies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | 3 | class SortingStrategy: 4 | # Line is a sequence of points: 5 | def sort(self, values) : pass 6 | 7 | # The various strategies: 8 | class AscendingSort(SortingStrategy): 9 | def sort(self, values): 10 | return sorted(values) 11 | 12 | class DescendingSort(SortingStrategy): 13 | def sort(self, values): 14 | return sorted(values, reverse=True) 15 | 16 | class ListSorter: 17 | def __init__(self, strategy): 18 | self.strategy = strategy 19 | 20 | def sort_list(self, values): 21 | return self.strategy.sort(values) 22 | 23 | def change_strategy(self, new_strategy): 24 | self.strategy = new_strategy 25 | -------------------------------------------------------------------------------- /Behavioral/Strategy/python/strategy_demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2.7 2 | 3 | from sorting_strategies import * 4 | 5 | sorter = ListSorter(AscendingSort()) 6 | values = [1, 2, 5, 8, 6, 3, 7, 4] 7 | print(sorter.sort_list(values)) 8 | sorter.change_strategy(DescendingSort()) 9 | print(sorter.sort_list(values)) 10 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/README.md: -------------------------------------------------------------------------------- 1 | Template Method Pattern 2 | 3 | Provides a solution for a problem when an algorithm consists of customizable parts and invariant parts 4 | It allows you to implement invariant parts of the algorithm in an abstract class with abstract (unimplemented) primitive 5 | operations representing the customizable parts of the algorithm. The subclasses customize the primitive operations 6 | 7 | Consequences: 8 | Code reuse for the invariant parts of algorithm 9 | Customization is restricted to the primitive operations 10 | Inverted control for customization -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/c#/DerivedOrder1.cs: -------------------------------------------------------------------------------- 1 | namespace TemplateMethod 2 | { 3 | public class DerivedOrder1 : BaseOrder 4 | { 5 | public DerivedOrder1(decimal basePrice) : base(basePrice) 6 | { 7 | 8 | } 9 | 10 | protected override bool ConfirmOrder(decimal price) 11 | { 12 | if (price > 0 && price < 10000) 13 | { 14 | return true; 15 | } 16 | return false; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/c#/DerivedOrder2.cs: -------------------------------------------------------------------------------- 1 | namespace TemplateMethod 2 | { 3 | public class DerivedOrder2 : BaseOrder 4 | { 5 | public DerivedOrder2(decimal basePrice) : base(basePrice) 6 | { 7 | 8 | } 9 | 10 | protected override bool ConfirmOrder(decimal price) 11 | { 12 | if (price >= 0 && price < 999) 13 | { 14 | return true; 15 | } 16 | return false; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/c#/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TemplateMethod 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Console.WriteLine("Starting..."); 10 | 11 | BaseOrder order1 = new DerivedOrder1(1000); 12 | 13 | if (!order1.PlaceOrder()) 14 | { 15 | Console.WriteLine("Failed placing the order..."); 16 | } 17 | 18 | BaseOrder order2 = new DerivedOrder2(1000); 19 | 20 | if (!order2.PlaceOrder()) 21 | { 22 | Console.WriteLine("Failed placing the order..."); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/c++/Operation.h: -------------------------------------------------------------------------------- 1 | #ifndef OPERATION_H 2 | #define OPERATION_H 3 | 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Operation 9 | { 10 | protected: 11 | int num1; 12 | int num2; 13 | 14 | public: 15 | Operation(int x, int y) 16 | { 17 | this->num1 = x; 18 | this->num2 = y; 19 | } 20 | 21 | virtual int doOperation() = 0; 22 | virtual char getCharOperator() = 0; 23 | string printOperation() 24 | { 25 | return "Operation: " + to_string(num1) + getCharOperator() + to_string(num2) + "=" + to_string(doOperation()); 26 | } 27 | }; 28 | 29 | 30 | #endif -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/c++/Subtraction.h: -------------------------------------------------------------------------------- 1 | #ifndef SUBTRACTION_H 2 | #define SUBTRACTION_H 3 | 4 | #include "Operation.h" 5 | 6 | class Subtraction:public Operation 7 | { 8 | public: 9 | Subtraction(int x, int y):Operation(x,y){ 10 | } 11 | 12 | int doOperation() override 13 | { 14 | return num1 - num2; 15 | } 16 | 17 | char getCharOperator() override 18 | { 19 | return '-'; 20 | } 21 | 22 | }; 23 | #endif -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/c++/Sum.h: -------------------------------------------------------------------------------- 1 | #ifndef SUM_H 2 | #define SUM_H 3 | 4 | #include "Operation.h" 5 | 6 | class Sum:public Operation 7 | { 8 | public: 9 | Sum(int x, int y):Operation(x,y){ 10 | } 11 | 12 | int doOperation() override 13 | { 14 | return num1 + num2; 15 | } 16 | 17 | char getCharOperator() override 18 | { 19 | return '+'; 20 | } 21 | 22 | }; 23 | #endif -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/c++/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "Subtraction.h" 4 | #include "Sum.h" 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | Operation * operation = new Sum(10,6); 11 | cout << operation->printOperation() << endl; 12 | delete operation; 13 | 14 | operation = new Subtraction(20, 7); 15 | cout << operation->printOperation() << endl; 16 | delete operation; 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/java/Defender.java: -------------------------------------------------------------------------------- 1 | /** 2 | * A defender is a player but has unique properties 3 | * 4 | * @author sherilpaulin 5 | * 6 | */ 7 | public class Defender extends Player { 8 | 9 | @Override 10 | public void heavyTraining() { 11 | System.out.println("This is a DEFENDER making heavy defence training"); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/java/Goalkeeper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * A goalkeeper is a player but has unique properties 3 | * 4 | * @author sherilpaulin 5 | * 6 | */ 7 | public class Goalkeeper extends Player { 8 | 9 | @Override 10 | public void heavyTraining() { 11 | System.out.println("This is a GOALKEEPER making heavy defence training"); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/java/Midfielder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * A midfielder is a player but has unique properties 3 | * 4 | * @author sherilpaulin 5 | * 6 | */ 7 | public class Midfielder extends Player { 8 | 9 | @Override 10 | public void heavyTraining() { 11 | System.out.println("This is a MIDFIELDER making heavy defence training"); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/java/TemplateMethodDemo.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | /** 4 | * same usage of this pattern 5 | * @author sherilpaulin 6 | * 7 | */ 8 | public class TemplateMethodDemo { 9 | public static void main(String[] args) { 10 | 11 | List players = new ArrayList(); 12 | 13 | players.add(new Defender("Sergio Ramos", 4)); 14 | players.add(new Midfielder("Luka Modric",10)); 15 | players.add(new Goalkeeper("Keylor Navas", 1)); 16 | 17 | players.stream().forEach(p -> p.permormTrainingSession()); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/kotlin/CaffeineBeverage.kt: -------------------------------------------------------------------------------- 1 | abstract class CaffeineBeverage { 2 | fun prepareRecipe() { 3 | boilWater() 4 | brew() 5 | pourInCup() 6 | addCondiments() 7 | } 8 | 9 | abstract fun brew() 10 | 11 | abstract fun addCondiments() 12 | 13 | fun boilWater() { 14 | println("Boil some water") 15 | } 16 | 17 | fun pourInCup() { 18 | println("Pour beverage in a cup") 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/kotlin/Coffee.kt: -------------------------------------------------------------------------------- 1 | class Coffee : CaffeineBeverage() { 2 | override fun brew() { 3 | println("Brew the coffee grinds") 4 | } 5 | 6 | override fun addCondiments() { 7 | println("Add sugar and milk") 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/kotlin/Tea.kt: -------------------------------------------------------------------------------- 1 | 2 | class Tea : CaffeineBeverage() { 3 | override fun brew() { 4 | println("Steep the teabag in the water") 5 | } 6 | 7 | override fun addCondiments() { 8 | println("Add lemon") 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/kotlin/TemplateMethodDemo.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | val tea = Tea() 3 | tea.prepareRecipe() 4 | 5 | val coffee = Coffee() 6 | coffee.prepareRecipe() 7 | } 8 | -------------------------------------------------------------------------------- /Behavioral/TemplateMethod/python/template_example.py: -------------------------------------------------------------------------------- 1 | from prepare_shake import * 2 | print("Preparing mango shake") 3 | mangoShakePreparation = MangoShakePreparation() 4 | mangoShakePreparation.prepare() 5 | print("Preparing pineapple shake") 6 | pineappleShakePreparation = PineappleShakePreparation() 7 | pineappleShakePreparation.prepare() 8 | print("Preparing detox shake") 9 | detoxShakePreparation = DetoxShakePreparation() 10 | detoxShakePreparation.prepare() 11 | -------------------------------------------------------------------------------- /Behavioral/Visitor/cpp/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "visitor.h" 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | DiscountVisitor dv; 8 | Drink drink(20); 9 | Candy candy(30); 10 | Book book(100); 11 | 12 | cout<getPrice()*(1 - 0.11); 5 | } 6 | 7 | double DiscountVisitor::visit(Candy *candy) { 8 | return candy->getPrice()*(1 - 0.3); 9 | } 10 | 11 | double DiscountVisitor::visit(Book *book) { 12 | return book->getPrice()*(1 - 0.2); 13 | } 14 | 15 | 16 | -------------------------------------------------------------------------------- /Behavioral/Visitor/java/Circle.java: -------------------------------------------------------------------------------- 1 | public class Circle implements Shape { 2 | private double radius; 3 | 4 | public Circle(double radius) { 5 | this.radius = radius; 6 | } 7 | 8 | @Override 9 | public void accept(ShapeVisitor visitor) { 10 | visitor.visit(this); 11 | } 12 | 13 | public double getRadius() { 14 | return radius; 15 | } 16 | 17 | public void setRadius(double radius) { 18 | this.radius = radius; 19 | } 20 | } -------------------------------------------------------------------------------- /Behavioral/Visitor/java/PrintAreaVisitor.java: -------------------------------------------------------------------------------- 1 | public class PrintAreaVisitor implements ShapeVisitor { 2 | @Override 3 | public void visit(Rectangle rectangle) { 4 | double area = rectangle.getLength() * rectangle.getWidth(); 5 | System.out.println("Rectangle area: " + area); 6 | } 7 | 8 | @Override 9 | public void visit(Circle circle) { 10 | double area = Math.PI * (circle.getRadius() * circle.getRadius()); 11 | System.out.println("Circle area: " + area); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Behavioral/Visitor/java/Rectangle.java: -------------------------------------------------------------------------------- 1 | public class Rectangle implements Shape { 2 | private double length; 3 | private double width; 4 | 5 | public Rectangle(double length, double width) { 6 | this.length = length; 7 | this.width = width; 8 | } 9 | 10 | @Override 11 | public void accept(ShapeVisitor visitor) { 12 | visitor.visit(this); 13 | } 14 | 15 | public double getLength() { 16 | return length; 17 | } 18 | 19 | public void setLength(double length) { 20 | this.length = length; 21 | } 22 | 23 | public double getWidth() { 24 | return width; 25 | } 26 | 27 | public void setWidth(double width) { 28 | this.width = width; 29 | } 30 | } -------------------------------------------------------------------------------- /Behavioral/Visitor/java/Shape.java: -------------------------------------------------------------------------------- 1 | public interface Shape { 2 | void accept(ShapeVisitor visitor); 3 | } -------------------------------------------------------------------------------- /Behavioral/Visitor/java/ShapeVisitor.java: -------------------------------------------------------------------------------- 1 | interface ShapeVisitor { 2 | void visit(Rectangle rectangle); 3 | void visit(Circle circle); 4 | } 5 | -------------------------------------------------------------------------------- /Behavioral/Visitor/java/VisitorDemo.java: -------------------------------------------------------------------------------- 1 | public class VisitorDemo { 2 | public static void main(String[] args) { 3 | ShapeVisitor visitor = new PrintAreaVisitor(); 4 | 5 | Rectangle rectangle = new Rectangle(2, 3); 6 | rectangle.accept(visitor); 7 | 8 | Circle circle = new Circle(1); 9 | circle.accept(visitor); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contribution 2 | * Contributions are always welcome. Language doesn't matter. Just make sure you're implementing design pattern. 3 | * PRs are welcome. To begin developing, follow the structure: 4 | 5 | > category/design pattern name/language-name/file_name.extension 6 | 7 | e.g 8 | 9 | > Creational/Abstract factory/python/abstract_factory.py 10 | * Don't forget to add README with explanation how pattern works, when to use and common usage of the pattern. 11 | * Adding image with UML diagram for design pattern would be very helpfull. 12 | -------------------------------------------------------------------------------- /Concurrency/Balking Pattern/Documentation.md: -------------------------------------------------------------------------------- 1 | The balking pattern is a software design which exectues action on an object only when its in a particular state. This is a great algorithm for objects which are know for baliking 2 | but for an unknown period of time. 3 | -------------------------------------------------------------------------------- /Concurrency/Balking Pattern/java/BalkingPattern.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Balking Pattern 3 | * ref: 4 | */ 5 | public class BalkingPattern { 6 | private boolean jobInProgress = false; 7 | 8 | public void job() { 9 | synchronized(this) { 10 | if (jobInProgress) { 11 | return; 12 | } 13 | jobInProgress = true; 14 | } 15 | // Code to execute job goes here 16 | // ... 17 | } 18 | 19 | void jobCompleted() { 20 | synchronized(this) { 21 | jobInProgress = false; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Concurrency/Concurrent Server/go/concurrent_server/Readme.md: -------------------------------------------------------------------------------- 1 | This is a very simple concurrent server that creates a new server thread for every client that makes a request. It has a very simple protocol: The client says "Hello", then sends an int that wants to be operated (in this case it subtracts one from the given number). Finally, the client says "Goodbye", which ends the execution of both the client and server thread instances. 2 | 3 | To try it out, in first place run the [tcp_server.go](server/main/tcp_server.go) file. Then, run as many Clients as you want, and send requests to the server form their consoles. 4 | 5 | This pattern is actually used by low load web servers, meaning that there aren't many requests, these requests are short and they don't have a high processor usage. -------------------------------------------------------------------------------- /Concurrency/Concurrent Server/java/README.md: -------------------------------------------------------------------------------- 1 | This is a very simple concurrent server that creates a new server thread for every client that makes a request. 2 | It has a very simple protocol: The client says "Hello", then sends an int that wants to be operated (in this case it subtracts 3 | one from the given number). Finally, the client says "Goodbye", which ends the execution of both the client and server thread 4 | instances. 5 | 6 | To try it out, in first place run the MainServer.java file. Then, run as many Clients as you want, and send requests to the 7 | server form their consoles. 8 | 9 | This pattern is actually used by low load web servers, meaning that there aren't many requests, these requests are short 10 | and they don't have a high processor usage. -------------------------------------------------------------------------------- /Concurrency/Creational/Singleton/java/SingletonLazyThreadSafe.java: -------------------------------------------------------------------------------- 1 | public class SingletonLazyThreadSafe { 2 | int value; 3 | 4 | public int getValue() { 5 | return value; 6 | } 7 | 8 | 9 | public void setValue(int value) { 10 | this.value = value; 11 | } 12 | 13 | private SingletonLazyThreadSafe() { 14 | } 15 | 16 | private static class InstanceHolder { 17 | private static final SingletonLazyThreadSafe INSTANCE = new SingletonLazyThreadSafe(); 18 | } 19 | 20 | public static SingletonLazyThreadSafe getInstance() { 21 | return SingletonLazyThreadSafe.InstanceHolder.INSTANCE; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Concurrency/Fan In/go/readme.md: -------------------------------------------------------------------------------- 1 | Fan-in Fan-out is a way of Multiplexing and Demultiplexing in golang. Fan-in refers to processing multiple input data and combining into a single entity. Fan-out is the exact opposite, dividing the data into multiple smaller chunks, distributing the work amongst a group of workers to parallelize CPU use and I/O. -------------------------------------------------------------------------------- /Concurrency/Guarded Suspension/java/GuardedSuspension.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Guarded Suspension 3 | * ref: 4 | */ 5 | public class GuardedSuspension { 6 | synchronized void guardedMethod() { 7 | while (!preCondition()) { // preCodition() is a method 8 | try { 9 | // Continue to wait 10 | wait(); 11 | // … 12 | } catch (InterruptedException e) { 13 | // … 14 | } 15 | } 16 | // Actual task implementation 17 | } 18 | synchronized void alterObjectStateMethod() { 19 | // Change the object state 20 | // … 21 | // Inform waiting threads 22 | notify(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Concurrency/Mutex/Mutex/java/Bank.java: -------------------------------------------------------------------------------- 1 | public class Bank { 2 | private int money; 3 | private Mutex lock; 4 | 5 | public Bank(int money, Mutex lock) { 6 | this.money = money; 7 | this.lock = lock; 8 | } 9 | 10 | public void withdrawl(int i) { 11 | try { 12 | lock.acquire(); 13 | money -= i; 14 | } catch (InterruptedException e) { 15 | e.printStackTrace(); 16 | } finally { 17 | lock.release(); 18 | } 19 | } 20 | 21 | public boolean isEmpty() { 22 | return money == 0; 23 | } 24 | } -------------------------------------------------------------------------------- /Concurrency/Mutex/Mutex/java/Mutex.java: -------------------------------------------------------------------------------- 1 | public class Mutex { 2 | private Object owner; 3 | 4 | public synchronized void acquire() throws InterruptedException { 5 | while (owner != null) { 6 | wait(); 7 | } 8 | owner = Thread.currentThread(); 9 | } 10 | public synchronized void release() { 11 | if (Thread.currentThread() == owner) { 12 | owner = null; 13 | notify(); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Concurrency/Mutex/Mutex/java/MutexExample.java: -------------------------------------------------------------------------------- 1 | public class MutexExample { 2 | public static void main(String[] args) { 3 | Mutex lock = new Mutex(); 4 | 5 | // The bank can only be accessed by one theif at a time 6 | Bank bank = new Bank(100, lock); 7 | Theif theifA = new Theif("Alice"); 8 | Theif theifB = new Theif("Bob"); 9 | theifA.rob(bank); 10 | theifB.rob(bank); 11 | theifA.start(); 12 | theifB.start(); 13 | } 14 | } -------------------------------------------------------------------------------- /Concurrency/Mutex/Mutex/java/Theif.java: -------------------------------------------------------------------------------- 1 | public class Theif extends Thread { 2 | private Bank bank; 3 | private String name; 4 | 5 | public Theif(String name) { this.name = name; } 6 | 7 | public void rob(Bank bank) { 8 | this.bank = bank; 9 | } 10 | 11 | @Override 12 | public void run() { 13 | int stealAmount = 10; 14 | 15 | while(!bank.isEmpty()) { 16 | bank.withdrawl(stealAmount); 17 | System.out.println(name + " is stealing " + stealAmount + " from the bank!"); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Concurrency/Observer/php/Observable.php: -------------------------------------------------------------------------------- 1 | observers[] = $observer; 9 | } 10 | 11 | function unregister($observerToRemove) 12 | { 13 | foreach($this->observers as $k => $observer) { 14 | if ($observer === $observerToRemove) { 15 | unset($this->observers[$k]); 16 | } 17 | } 18 | } 19 | 20 | function dispatch() 21 | { 22 | foreach($this->observers as $observer) { 23 | $observer->fire(); 24 | } 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Concurrency/Observer/php/Observer.php: -------------------------------------------------------------------------------- 1 | name = $name; 9 | } 10 | 11 | function fire() 12 | { 13 | echo "fire spotted by $this->name" . PHP_EOL; 14 | } 15 | } -------------------------------------------------------------------------------- /Concurrency/Observer/php/Test.php: -------------------------------------------------------------------------------- 1 | register($observerMike); 13 | $observable->register($observerBetty); 14 | $observable->register($observerFlip); 15 | $observable->register($observerFlap); 16 | 17 | $observable->dispatch(); 18 | 19 | echo 'unregister Flip and Flap' . PHP_EOL; 20 | $observable->unregister($observerFlip); 21 | $observable->unregister($observerFlap); 22 | 23 | $observable->dispatch(); 24 | -------------------------------------------------------------------------------- /Concurrency/Observer/python/Launcher.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | sys.dont_write_bytecode = True; 4 | 5 | from Subscriber import Subscriber 6 | from Publisher import Publisher 7 | 8 | 9 | def main(): 10 | pub = Publisher(['lunch', 'dinner']) 11 | bob = Subscriber('Bob') 12 | alice = Subscriber('Alice') 13 | john = Subscriber('John') 14 | 15 | pub.register("lunch", bob) 16 | pub.register("dinner", alice) 17 | pub.register("lunch", john) 18 | pub.register("dinner", john) 19 | 20 | pub.dispatch("lunch", "It's lunchtime!") 21 | pub.dispatch("dinner", "Dinner is served") 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /Concurrency/Observer/python/Subscriber.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | sys.dont_write_bytecode = True; 4 | 5 | class Subscriber: 6 | def __init__(self, name): 7 | self.name = name 8 | 9 | def update(self, message): 10 | print('{} got message "{}"'.format(self.name, message)) 11 | 12 | -------------------------------------------------------------------------------- /Concurrency/Semaphores/java/Semaphores/Semaphore.java: -------------------------------------------------------------------------------- 1 | package Semaphores; 2 | 3 | /** 4 | * Although java.util.concurrent has its own semaphore class, this is a simpler implementation of a semaphore 5 | */ 6 | public class Semaphore { 7 | 8 | /** 9 | * Semaphore's count, it represent how many threads can access the resource at the same time 10 | */ 11 | private int count; 12 | 13 | public Semaphore(int count) { 14 | this.count = count; 15 | } 16 | 17 | public synchronized void acquire() { 18 | count--; 19 | if(count < 0) { 20 | try { 21 | wait(); 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | } 27 | 28 | public synchronized void release() { 29 | count++; 30 | if(count <= 0) { 31 | notify(); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Concurrency/Semaphores/java/Semaphores/multiplex/MultiplexThread.java: -------------------------------------------------------------------------------- 1 | package Semaphores.multiplex; 2 | 3 | public class MultiplexThread extends Thread { 4 | 5 | public MultiplexThread() { 6 | } 7 | 8 | public void run() { 9 | //Before calling the method, the thread acquires the permit, after calling it, it releases it. 10 | Multiplex.semaphore.acquire(); 11 | Multiplex.a(); 12 | Multiplex.semaphore.release(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Concurrency/Semaphores/java/Semaphores/signaling/SignalingThread.java: -------------------------------------------------------------------------------- 1 | package Semaphores.signaling; 2 | 3 | public class SignalingThread extends Thread { 4 | 5 | private int type; 6 | 7 | public final static int TYPE_A = 1; 8 | 9 | public final static int TYPE_B = 0; 10 | 11 | public SignalingThread(int tipo) { 12 | this.type = tipo; 13 | } 14 | 15 | public void run() { 16 | //As you always want a() to be called first, the thread that calls it releases the permit after calling a. 17 | if(type == TYPE_A) { 18 | Signaling.a(); 19 | Signaling.semaphore.release(); 20 | } 21 | if(type == TYPE_B) { 22 | Signaling.semaphore.acquire(); 23 | Signaling.b(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/AbstractFactoryUML.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Creational/Abstract Factory/csharp/AbstractFactoryUML.PNG -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/csharp/Cars/Car.cs: -------------------------------------------------------------------------------- 1 | namespace csharp.Factory 2 | { 3 | public interface Car 4 | { 5 | string Accelerate(); 6 | string Break(); 7 | string GetBrand(); 8 | string GetColor(); 9 | string GetModel(); 10 | int GetCurrentSpeed(); 11 | } 12 | } -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/csharp/Cars/Models/Astra.cs: -------------------------------------------------------------------------------- 1 | using csharp.Cars.Properties; 2 | 3 | namespace csharp.Cars.Models 4 | { 5 | public class Astra : Opel 6 | { 7 | private Model Model { get; } 8 | 9 | public Astra(Color color) : base(color, 260, 10) 10 | { 11 | Model = Model.ASTRA; 12 | } 13 | 14 | public override string GetModel() 15 | { 16 | return Model.ToString(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/csharp/Cars/Models/Corsa.cs: -------------------------------------------------------------------------------- 1 | using csharp.Cars.Properties; 2 | 3 | namespace csharp.Cars.Models 4 | { 5 | public class Corsa : Opel 6 | { 7 | private Model Model { get; } 8 | 9 | public Corsa(Color color) : base(color, 180, 5) 10 | { 11 | Model = Model.CORSA; 12 | } 13 | 14 | public override string GetModel() 15 | { 16 | return Model.ToString(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/csharp/Cars/Properties/Color.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace csharp.Cars.Properties 6 | { 7 | public enum Color 8 | { 9 | BLACK, 10 | WHITE, 11 | GREY, 12 | PINK 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/csharp/Cars/Properties/Model.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace csharp.Cars.Properties 6 | { 7 | public enum Model 8 | { 9 | CORSA, 10 | ASTRA, 11 | VECTRA, 12 | ZAFIRA 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/csharp/Factory/AbstractFactory.cs: -------------------------------------------------------------------------------- 1 | using csharp.Cars.Properties; 2 | 3 | namespace csharp.Factory 4 | { 5 | public abstract class AbstractFactory 6 | { 7 | // type T because the AbstractFactory doesn't need a type now but it will have to return the type when the interface is implemented 8 | public abstract T Create(Model model, Color color); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/csharp/Factory/CarFactory.cs: -------------------------------------------------------------------------------- 1 | using csharp.Cars.Models; 2 | using csharp.Cars.Properties; 3 | 4 | namespace csharp.Factory 5 | { 6 | public class CarFactory : AbstractFactory 7 | { 8 | public override Car Create(Model model, Color color) 9 | { 10 | switch(model) 11 | { 12 | case Model.ASTRA: 13 | return new Astra(color); 14 | default: 15 | return new Corsa(color); 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/csharp/csharp/csharp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.2 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/CalculatorFactory/Add.java: -------------------------------------------------------------------------------- 1 | //package com.nk.springboot.designpatterns.Factory; 2 | 3 | public class Add extends Calculator { 4 | 5 | @Override 6 | public int calculate() { 7 | // TODO Auto-generated method stub 8 | return a + b; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/CalculatorFactory/Calculator.java: -------------------------------------------------------------------------------- 1 | //package com.nk.springboot.designpatterns.Factory; 2 | 3 | public abstract class Calculator { 4 | protected int a, b; 5 | public abstract int calculate() throws Exception; 6 | 7 | 8 | } 9 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/CalculatorFactory/Divide.java: -------------------------------------------------------------------------------- 1 | //package com.nk.springboot.designpatterns.Factory; 2 | 3 | public class Divide extends Calculator { 4 | 5 | @Override 6 | public int calculate(){ 7 | // TODO Auto-generated method stub 8 | if (b == 0) 9 | { 10 | throw new ArithmeticException("Error. Cannot divide by zero"); 11 | } 12 | else 13 | { 14 | return a / b; 15 | } 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/CalculatorFactory/GetCalcFactory.java: -------------------------------------------------------------------------------- 1 | //package com.nk.springboot.designpatterns.Factory; 2 | 3 | public class GetCalcFactory { 4 | 5 | public Calculator getCalc(String operation) 6 | { 7 | operation = operation.toLowerCase(); 8 | if(operation.equals("add")) 9 | { 10 | return new Add(); 11 | } 12 | else if(operation.equals("subtract")) 13 | { 14 | return new Subtract(); 15 | } 16 | else if(operation.equals("multiply")) 17 | { 18 | return new Multiply(); 19 | } 20 | else if(operation.equals("divide")) 21 | { 22 | return new Divide(); 23 | } 24 | else if(operation.equals("power")) 25 | { 26 | return new Power(); 27 | } 28 | else 29 | { 30 | return null; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/CalculatorFactory/Multiply.java: -------------------------------------------------------------------------------- 1 | //package com.nk.springboot.designpatterns.Factory; 2 | 3 | public class Multiply extends Calculator { 4 | 5 | @Override 6 | public int calculate() throws Exception { 7 | // TODO Auto-generated method stub 8 | return a * b; 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/CalculatorFactory/Power.java: -------------------------------------------------------------------------------- 1 | //package com.nk.springboot.designpatterns.Factory; 2 | 3 | public class Power extends Calculator { 4 | 5 | @Override 6 | public int calculate() throws Exception { 7 | return (int)Math.pow(a, b); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/CalculatorFactory/Subtract.java: -------------------------------------------------------------------------------- 1 | //package com.nk.springboot.designpatterns.Factory; 2 | 3 | public class Subtract extends Calculator 4 | { 5 | 6 | @Override 7 | public int calculate() { 8 | // TODO Auto-generated method stub 9 | return a - b; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/FactoryPattern.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Creational/Abstract Factory/java/FactoryPattern.jpg -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/Vehicle.java: -------------------------------------------------------------------------------- 1 | public interface Vehicle { 2 | void drive(); 3 | } 4 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/VehicleFactory.java: -------------------------------------------------------------------------------- 1 | public class VehicleFactory { 2 | 3 | public static Vehicle getVehicle(int option){ 4 | Vehicle vehicle = null; 5 | if( option == 1) vehicle = new Car(); 6 | else if ( option == 2) vehicle = new Airplane(); 7 | else if ( option == 3) vehicle = new Bicycle(); 8 | return vehicle; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/FactoryCar.java: -------------------------------------------------------------------------------- 1 | public interface FactoryCar { 2 | 3 | Minivan createMinivan(); 4 | Pickup createPickup(); 5 | } 6 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/GMCFactory.java: -------------------------------------------------------------------------------- 1 | public class GMCFactory implements FactoryCar { 2 | 3 | public Minivan createMinivan() { 4 | 5 | return new Savana(); 6 | } 7 | 8 | public Pickup createPickup() { 9 | 10 | return new Sierra(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/Minivan.java: -------------------------------------------------------------------------------- 1 | public interface Minivan { 2 | 3 | public void printName(); 4 | public void printFuel(); 5 | } 6 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/Pickup.java: -------------------------------------------------------------------------------- 1 | public interface Pickup { 2 | 3 | public void printName(); 4 | public void printFuel(); 5 | } 6 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/Savana.java: -------------------------------------------------------------------------------- 1 | public class Savana implements Minivan { 2 | 3 | public void printName() { 4 | System.out.println("Savana 1500 Cargo"); 5 | 6 | } 7 | 8 | public void printFuel() { 9 | System.out.println("Flex"); 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/Sienna.java: -------------------------------------------------------------------------------- 1 | public class Sienna implements Minivan { 2 | 3 | public void printName() { 4 | 5 | System.out.println("Sienna"); 6 | } 7 | 8 | public void printFuel() { 9 | 10 | System.out.println("Gasoline"); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/Sierra.java: -------------------------------------------------------------------------------- 1 | public class Sierra implements Pickup { 2 | 3 | public void printName() { 4 | 5 | System.out.println("GMC Sierra 1500 SLT Ext. Cab 4WD"); 6 | } 7 | 8 | public void printFuel() { 9 | 10 | System.out.println("Flex"); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/Tacoma.java: -------------------------------------------------------------------------------- 1 | public class Tacoma implements Pickup { 2 | 3 | public void printName() { 4 | 5 | System.out.println("TACOMA"); 6 | } 7 | 8 | public void printFuel() { 9 | 10 | System.out.println("Diesel"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/ToyotaFactory.java: -------------------------------------------------------------------------------- 1 | public class ToyotaFactory implements FactoryCar { 2 | 3 | public Minivan createMinivan() { 4 | 5 | return new Sienna(); 6 | } 7 | 8 | public Pickup createPickup() { 9 | 10 | return new Tacoma(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Creational/Abstract Factory/java/example1/readme.md: -------------------------------------------------------------------------------- 1 | # Abstract Factory 2 | 3 | Has primary responsibility for reducing the use of `new`, this pattern provide a interface to create a family objects. 4 | 5 | How in example we have a family of Car( Minivan and Pickups ), but can have several implementations how: 6 | 7 | - ToyotaFactory 8 | - GMCFactory 9 | 10 | With this pattern we can create any CarFactory, just implemented it. 11 | 12 | See follow classes: 13 | 14 | - `FactoryCar` 15 | - `MiniVan` 16 | - `Pickup` 17 | - Implementations for `Minivan` and `Pickup` 18 | - `GMCFactory` 19 | - `ToyotaFactory` -------------------------------------------------------------------------------- /Creational/Abstract Factory/python/abstract_factory.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Creational/Abstract Factory/python/abstract_factory.py -------------------------------------------------------------------------------- /Creational/Builder/Csharp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace BuilderPattern 8 | { 9 | class Program 10 | { 11 | static void Main(string[] args) 12 | { 13 | Console.WriteLine("Normal builder:"); 14 | var car = new Car(); 15 | car.SetColor("red"); 16 | car.SetPower(125); 17 | Console.WriteLine(car); 18 | Console.WriteLine("------------"); 19 | Console.WriteLine("Fluent builder:"); 20 | var car2 = new Car().SetColorFluent("green").SetPowerFluent(200); 21 | Console.WriteLine(car2); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Creational/Builder/README.md: -------------------------------------------------------------------------------- 1 | # Builder Pattern 2 | 3 | > Separate the construction of a complex object form its representation so that the same construction process can create different representations. 4 | 5 | This pattern is commonly used as a means to make object creation easier. Long constructors can make Objects hard to use - by providing a Builder, objects can be easier to use without exposing Mutability in your object. 6 | 7 | For more information, Wikipedia provides a great overview of the pattern: [Wikipedia Article](https://en.wikipedia.org/wiki/Builder_pattern) 8 | -------------------------------------------------------------------------------- /Creational/Builder/java/BuilderWithLombok.java: -------------------------------------------------------------------------------- 1 | package com.example.tutpoint.learn; 2 | 3 | import lombok.Builder; 4 | import lombok.Data; 5 | 6 | /** 7 | * @Builder will generate all the boiler plate required to generate a builder for the class 8 | */ 9 | @Builder 10 | @Data 11 | public class BuilderWithLombok { 12 | String name; 13 | int age; 14 | String address; 15 | } 16 | 17 | class BuilderWithLombokInstance { 18 | static void main(String[] args) { 19 | BuilderWithLombok object = BuilderWithLombok.builder() 20 | .name("Name") 21 | .age(11) 22 | .address("1, ABC") 23 | .build(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Creational/Builder/java/DeveloperBuildUsage.java: -------------------------------------------------------------------------------- 1 | public class DeveloperBuildUsage { 2 | 3 | public static void main(String[] args) { 4 | Developer developer = Developer.builder() 5 | .name("José") 6 | .programingLanguage("Java") 7 | .operationSystem("Windows") 8 | .build(); 9 | Developer developer2 = Developer.builder() 10 | .name("Augusto") 11 | .programingLanguage("Java") 12 | .operationSystem("Linux") 13 | .build(); 14 | System.out.println(developer.toString()); 15 | System.out.println(developer2.toString()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Creational/Builder/javascript/README.md: -------------------------------------------------------------------------------- 1 | # A Note On JavaScript 2 | 3 | The Builder pattern is most commonly referred to as the Constructor pattern. Since most everything in JavaScript, this pattern most often involved _object_ constructors. These constructors are used to control objection creation with arguments values for properties and methods as well as preparing the object for use. 4 | 5 | There are two examples given; one for es5 and earlier verions that relies on a generic constructor function and an es6 example that uses the `class` syntax and built-in constructor method. -------------------------------------------------------------------------------- /Creational/Constructor/README.md: -------------------------------------------------------------------------------- 1 | # Constructor Pattern 2 | 3 | > In classical object-oriented programming languages, a constructor is a special method used to initialize a newly created object once memory has been allocated for it. 4 | 5 | [The Constructor Pattern](https://www.oreilly.com/library/view/learning-javascript-design/9781449334840/ch09s01.html) 6 | -------------------------------------------------------------------------------- /Creational/Constructor/java/Constructor.java: -------------------------------------------------------------------------------- 1 | public class Constructor { 2 | private int name; 3 | 4 | public Constructor() { 5 | // construct the 'Constructor' object 6 | } 7 | 8 | public Constructor(String name) { 9 | // constructors can be overloaded 10 | this.name = name; 11 | } 12 | } -------------------------------------------------------------------------------- /Creational/Constructor/java/PrivateConstructor.java: -------------------------------------------------------------------------------- 1 | public class PrivateConstructor { 2 | private PrivateConstructor() { 3 | 4 | /* 5 | * Classes that are not meant to be instantiated 6 | * should have a private constructor to prevent 7 | * accidental instantiation, some examples include: 8 | * 9 | * - a class that is a collection of static functions 10 | * - classes for which we want a more readable 11 | * instantiation method (e.g. 12 | * 'ArrayList.createWithCapacity(5)') 13 | * - singletons 14 | */ 15 | } 16 | } -------------------------------------------------------------------------------- /Creational/Constructor/python/constructor.py: -------------------------------------------------------------------------------- 1 | # Constructors are used for instantiating an object. 2 | # It initializes the values to the data members of the class 3 | # when an object of that class is being created 4 | 5 | class Car: 6 | # constructor 7 | def __init__(self, model, year, miles): 8 | # self is a reference to the object itself 9 | self.model = model 10 | self.year = year 11 | self.miles = miles 12 | 13 | # method for printing data members 14 | def printDetails(self): 15 | print(self.model, 'has done', self.miles, 'miles') 16 | 17 | # instantiating an object of the class 18 | obj = Car("Jeep", 2009, 50000) 19 | 20 | # calling the instance method 21 | obj.printDetails() 22 | 23 | -------------------------------------------------------------------------------- /Creational/Constructor/swift/constructor.swift: -------------------------------------------------------------------------------- 1 | /// Constructors are used for instantiating an object. 2 | /// It initializes the values to the data members of the class 3 | /// when an object of that class is being created 4 | 5 | class Car { 6 | var model: String 7 | var year: Int 8 | var miles: Int 9 | 10 | 11 | // MARK: - Constructor 12 | 13 | init(model: String, year: Int, miles: Int) { 14 | self.model = model 15 | self.year = year 16 | self.miles = miles 17 | } 18 | } 19 | 20 | // instantiating an object of the class 21 | let obj = Car("Jeep", 2009, 50000) 22 | 23 | -------------------------------------------------------------------------------- /Creational/Dependency Injection/CSharp/.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | obj 3 | .idea -------------------------------------------------------------------------------- /Creational/Dependency Injection/CSharp/DI_Example.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.0 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Creational/Dependency Injection/CSharp/global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "3.0.100" 4 | } 5 | } -------------------------------------------------------------------------------- /Creational/Dependency Injection/java/DependencyInjectorPattern.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Creational/Dependency Injection/java/DependencyInjectorPattern.java -------------------------------------------------------------------------------- /Creational/Factory-Method-PT[BR]/factory_method.py: -------------------------------------------------------------------------------- 1 | class animals(): 2 | class galinha(): 3 | info = "Isso é uma galinha" 4 | class cachorro(): 5 | info = "Isso é um cachorro" 6 | class pato(): 7 | info = "isso é um pato" 8 | def fabricar_animais(tipo): 9 | if tipo == "galinha": 10 | return animals.galinha 11 | elif tipo == "cachorro": 12 | return animals.cachorro 13 | elif tipo == "pato": 14 | return animals.pato 15 | else: 16 | raise AssertionError("Tipo de animal não existe") 17 | lista =[] 18 | while True: 19 | info = input("Qual animal você quer na sua fazenda?\n") 20 | animal = fabricar_animais(info) 21 | lista.append(animal.info) 22 | print(lista) -------------------------------------------------------------------------------- /Creational/Factory-Method-PT[BR]/readme.md: -------------------------------------------------------------------------------- 1 | # This is a code of Factory Method 2 | 3 | ##### This code is written in portuguese, directly from a design pattern subject of my college. 4 | 5 | ##### Run code 6 | 7 | python3 factory_method.py 8 | 9 | ##### Usage 10 | 11 | Just type the name of one of the classes, and then the code will iterate and will work just like an usual factory method code. 12 | -------------------------------------------------------------------------------- /Creational/Factory-Method/Java/IPizzeria.java: -------------------------------------------------------------------------------- 1 | public interface IPizzeria { 2 | 3 | Pizza crearPizza(String especialidad); 4 | 5 | } 6 | -------------------------------------------------------------------------------- /Creational/Factory-Method/Java/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | MiPizzeria pizzeria = new MiPizzeria(); 6 | 7 | Pizza hawaiana = pizzeria.crearPizza("Hawaiana"); 8 | Pizza peperoni = pizzeria.crearPizza("Peperoni"); 9 | Pizza OrillaRellena = pizzeria.crearPizza("Peperoni orilla rellena"); 10 | 11 | System.out.println(peperoni); 12 | System.out.println(hawaiana); 13 | System.out.println(OrillaRellena); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Creational/Factory-Method/Java/MiPizzeria.java: -------------------------------------------------------------------------------- 1 | public class MiPizzeria implements IPizzeria { 2 | 3 | @Override 4 | public Pizza crearPizza(String tipo) { 5 | if(tipo.equals("Peperoni")) 6 | return new Pizza(8, "Peperoni"); 7 | if(tipo.equals("Hawaiana")) 8 | return new Pizza(8, "Hawaiana"); 9 | if(tipo.equals("Peperoni orilla rellena")) 10 | return new PizzaOrillaRellena(18, "peperoni"); 11 | return null; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Creational/Factory-Method/Java/Pizza.java: -------------------------------------------------------------------------------- 1 | public class Pizza{ 2 | 3 | private int rebanadas; 4 | private String especialidad; 5 | 6 | public Pizza(int rebanadas, String especialidad){ 7 | this.rebanadas = rebanadas; 8 | this.especialidad = especialidad; 9 | } 10 | 11 | @Override 12 | public String toString() { 13 | return "Rebanadas: "+this.rebanadas+" Especialidad: "+this.especialidad; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Creational/Factory-Method/Java/PizzaOrillaRellena.java: -------------------------------------------------------------------------------- 1 | public class PizzaOrillaRellena extends Pizza { 2 | 3 | public PizzaOrillaRellena(int rebanadas, String especialidad) { 4 | super(rebanadas, especialidad); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Creational/Factory-Method/README.md: -------------------------------------------------------------------------------- 1 | # Factory Method 2 | 3 | This method encapsulates the creation of objects, letting the subclass decide which objects to create. 4 | 5 | [![N|Solid](https://refactoring.guru/images/patterns/diagrams/factory-method/structure.png)](https://refactoring.guru/design-patterns/factory-method) 6 | 7 | -------------------------------------------------------------------------------- /Creational/Factory-Method/cSharp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace design_patterns 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Console.WriteLine("Hi! Creating vehicles through the Factory Method: "); 10 | 11 | VehicleFactory factory = new VehicleFactory(); 12 | String name = "Ferrari 488"; 13 | String via = "land"; 14 | factory.GetVehicle(name, via); 15 | 16 | Console.WriteLine("Created {0}", factory.GetType().Name); 17 | 18 | Console.ReadKey(); 19 | 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Creational/Factory-Method/php/factory-method.php: -------------------------------------------------------------------------------- 1 | makeClothing(); 35 | print $clothing->getClothing(); // Gives a result of "Pretty T-shirt"; 36 | -------------------------------------------------------------------------------- /Creational/Factory/C++/factory.cpp: -------------------------------------------------------------------------------- 1 | # include "factory.h" 2 | 3 | int main(void) 4 | { 5 | // Factory needs to know which type of object to return. 6 | Computer * myLaptop = ComputerFactory.NewComputer("laptop"); 7 | Computer * myDesktop = ComputerFactory.NewComputer("desktop") 8 | 9 | // If a change is made to any derived class of Computer, or a new Computer subtype is added, the implementation for NewComputer() is the only code that needs to be recompiled. 10 | // Everyone who uses the factory will only care about the interface, which should remain consistent throughout the life of the application. 11 | } -------------------------------------------------------------------------------- /Creational/Factory/Dart/factory.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | abstract class Shape { 4 | factory Shape(String type) { 5 | if(type == 'circle') return Circle(2); 6 | if(type == 'square') return Square(2); 7 | throw "Can't create $type"; 8 | } 9 | num get area; 10 | } 11 | 12 | class Circle implements Shape { 13 | final num radius; 14 | Circle(this.radius); 15 | num get area => pi * pow(radius, 2); 16 | } 17 | 18 | class Square implements Shape { 19 | final num side; 20 | Square(this.side); 21 | num get area => pow(side, 2) / 2; 22 | } 23 | 24 | main() { 25 | try { 26 | print(Shape('circle').area); 27 | print(Shape('square').area); 28 | print(Shape('triangle').area); 29 | } catch (e) { 30 | print(e); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Creational/Factory/d/Logger.d: -------------------------------------------------------------------------------- 1 | 2 | import std.stdio : writeln; 3 | 4 | class GenericLogger { 5 | private: 6 | string theClass; 7 | public: 8 | this(string theClass) { 9 | this.theClass = theClass; 10 | } 11 | 12 | void info(string s) { 13 | writeln(theClass ~ ": INFO: " ~ s); 14 | } 15 | } 16 | 17 | // 18 | // A simple factory that is used to track the source of a log message. 19 | // 20 | class LoggerFactory { 21 | public: 22 | static GenericLogger getLogger(string theClass) { 23 | return new GenericLogger(theClass); 24 | } 25 | } 26 | 27 | void main() { 28 | GenericLogger log = LoggerFactory.getLogger("Logger.d"); 29 | log.info("This is a log message"); 30 | } 31 | -------------------------------------------------------------------------------- /Creational/Factory/elixir/shape_factory.ex: -------------------------------------------------------------------------------- 1 | defmodule ShapeFactory do 2 | def create(:circle, radius), do: {:circle, radius} 3 | def create(:rectangle, width, height), do :{:rectangle, width, height} 4 | def create(:square, size), do: {:square, size} 5 | end 6 | 7 | defmodule Shapes do 8 | circle = ShapeFactory.create(:circle, 5) 9 | rectangle = ShapeFactory.create(:rectangle, 5) 10 | square = ShapeFactory.create(:square, 5) 11 | end -------------------------------------------------------------------------------- /Creational/Factory/go/book_factory.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | ) 7 | 8 | type Book struct { 9 | Title string 10 | Author string 11 | Pages int 12 | } 13 | 14 | func BookFactory(title string, author string, pages int) Book { 15 | return Book{title, author, pages} 16 | } 17 | 18 | func main() { 19 | new_book := BookFactory("Harry Potter and the Philosopher's Stone", "J.K. Rawling", 223) 20 | fmt.Println(new_book) 21 | fmt.Println(reflect.TypeOf(new_book)) 22 | } 23 | -------------------------------------------------------------------------------- /Creational/Factory/java/Chassis.java: -------------------------------------------------------------------------------- 1 | public interface Chassis { 2 | 3 | public final String chassis = "Chassis"; 4 | 5 | public Chassis getChassisType(); 6 | 7 | public void settChassisType(String vehicleChassis); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Creational/Factory/java/Circle.java: -------------------------------------------------------------------------------- 1 | public class Circle implements Shape { 2 | 3 | @Override 4 | public void draw() { 5 | System.out.println("Inside Circle::draw() method."); 6 | } 7 | } -------------------------------------------------------------------------------- /Creational/Factory/java/Engine.java: -------------------------------------------------------------------------------- 1 | import java.util.Date; 2 | 3 | public interface Engine { 4 | 5 | public void setEngineCylinders(int engineCylinders); 6 | 7 | public void setEngineManufacturedDate(Date date); 8 | 9 | public void setEngineManufacturer(String manufacturer); 10 | 11 | public void setEngineMake(String engineMake); 12 | 13 | public void setEngineModel(String engineModel); 14 | 15 | public void setDriveTrain(String driveTrain); 16 | 17 | public void setEngineType(String fuel); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Creational/Factory/java/ExteriorFeature.java: -------------------------------------------------------------------------------- 1 | public class ExteriorFeature implements Feature { 2 | 3 | private String exteriorFeature; 4 | 5 | ExteriorFeature() { 6 | exteriorFeature = "Generic"; 7 | } 8 | 9 | ExteriorFeature(String exteriorFeature) { 10 | this.exteriorFeature = exteriorFeature; 11 | } 12 | 13 | public String getFeature() { 14 | return exteriorFeature; 15 | } 16 | 17 | public void setFeature(String exteriorFeature) { 18 | this.exteriorFeature = exteriorFeature; 19 | } 20 | 21 | public String toString (){ 22 | return "Exterior [" + exteriorFeature + "]" + "\n"; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Creational/Factory/java/Feature.java: -------------------------------------------------------------------------------- 1 | public interface Feature { 2 | 3 | public String getFeature(); 4 | 5 | public void setFeature(String feature); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /Creational/Factory/java/InteriorFeature.java: -------------------------------------------------------------------------------- 1 | public class InteriorFeature implements Feature { 2 | 3 | private String interiorFeature; 4 | 5 | InteriorFeature() { 6 | interiorFeature = "Generic"; 7 | } 8 | 9 | InteriorFeature(String interiorFeature) { 10 | this.interiorFeature = interiorFeature; 11 | } 12 | 13 | public String getFeature() { 14 | return interiorFeature; 15 | } 16 | 17 | public void setFeature(String interiorFeature) { 18 | this.interiorFeature = interiorFeature; 19 | } 20 | 21 | @Override 22 | public String toString() { 23 | return "Interior [" + interiorFeature + "]" + "\n"; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Creational/Factory/java/Rectangle.java: -------------------------------------------------------------------------------- 1 | public class Rectangle implements Shape { 2 | 3 | @Override 4 | public void draw() { 5 | System.out.println("Inside Rectangle::draw() method."); 6 | } 7 | } -------------------------------------------------------------------------------- /Creational/Factory/java/Shape.java: -------------------------------------------------------------------------------- 1 | public interface Shape { 2 | void draw(); 3 | } 4 | -------------------------------------------------------------------------------- /Creational/Factory/java/ShapeFactory.java: -------------------------------------------------------------------------------- 1 | public class ShapeFactory { 2 | 3 | //use getShape method to get object of type shape 4 | public Shape getShape(String shapeType){ 5 | if(shapeType == null){ 6 | return null; 7 | } 8 | if(shapeType.equalsIgnoreCase("CIRCLE")){ 9 | return new Circle(); 10 | 11 | } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ 12 | return new Rectangle(); 13 | 14 | } else if(shapeType.equalsIgnoreCase("SQUARE")){ 15 | return new Square(); 16 | } 17 | 18 | return null; 19 | } 20 | } -------------------------------------------------------------------------------- /Creational/Factory/java/Square.java: -------------------------------------------------------------------------------- 1 | public class Square implements Shape { 2 | 3 | @Override 4 | public void draw() { 5 | System.out.println("Inside Square::draw() method."); 6 | } 7 | } -------------------------------------------------------------------------------- /Creational/Factory/java/VehicleChassis.java: -------------------------------------------------------------------------------- 1 | public class VehicleChassis implements Chassis { 2 | 3 | private String chassisName; 4 | 5 | public VehicleChassis() { 6 | this.chassisName = chassis; 7 | } 8 | 9 | public VehicleChassis(String chassisName) { 10 | this.chassisName = chassisName; 11 | } 12 | 13 | @Override 14 | public Chassis getChassisType() { 15 | return this; 16 | } 17 | 18 | @Override 19 | public void settChassisType(String vehicleChassis) { 20 | chassisName = vehicleChassis; 21 | } 22 | 23 | public String toString() { 24 | return "Chassis Name : Chassis"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Creational/Factory/java/VehicleFrame.java: -------------------------------------------------------------------------------- 1 | public class VehicleFrame implements Chassis { 2 | 3 | private String vehicleFrameType; 4 | 5 | public VehicleFrame() { 6 | this.vehicleFrameType = "Unibody"; 7 | } 8 | 9 | public VehicleFrame(String vehicleFrameType) { 10 | this.vehicleFrameType = vehicleFrameType; 11 | } 12 | 13 | @Override 14 | public Chassis getChassisType() { 15 | return this; 16 | } 17 | 18 | @Override 19 | public void settChassisType(String vehicleFrameType) { 20 | this.vehicleFrameType = vehicleFrameType; 21 | } 22 | 23 | public String toString() { 24 | return "Chassis: " + chassis + "\n" + 25 | "Vehicle Frame: " + vehicleFrameType +"\n"; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Creational/Factory/php/Book.php: -------------------------------------------------------------------------------- 1 | author = $author; 8 | $this->title = $title; 9 | } 10 | public function getBookDetails(){ 11 | return $this->title.' - '.$this->author; 12 | } 13 | 14 | } 15 | class BookFactory{ 16 | public static function createBook($title, $author){ 17 | return new Book($title, $author); 18 | } 19 | } 20 | $book1 = BookFactory::createBook("Alice's Adventures in Wonderland", "Lewis Carroll"); 21 | $book2 = BookFactory::createBook("The Book of the Courtier", "Baldassare Castiglione"); 22 | 23 | print_r($book1->getBookDetails()); 24 | print_r($book2->getBookDetails()); 25 | -------------------------------------------------------------------------------- /Creational/Factory/python/Readme.md: -------------------------------------------------------------------------------- 1 | ### How it Works 2 | Simply put, the Factory Method pattern can be used to create an interface for a method, leaving the implementation to the class that gets 3 | instantiated. 4 | 5 | ### Usage 6 | Used in most of the pupular web frameworks. In Django, for example, in a contact form of a web page, the subject and the message 7 | fields are created using the same form factory (CharField()), even though they have different implementations according to their purposes. 8 | -------------------------------------------------------------------------------- /Creational/Factory/ruby/README.md: -------------------------------------------------------------------------------- 1 | # Factory Pattern 2 | 3 | This example implements the Factory pattern to hide from the consumer the complexity of initializing different 4 | types of shapes. 5 | 6 | Instead it provides a single method to generate random instance of any of given subclasses of `Shape` which then 7 | can be used by the consumer (e.g. to output the properties of the shapes). -------------------------------------------------------------------------------- /Creational/LazyInitialization/java/LazyInitializationPattern.java: -------------------------------------------------------------------------------- 1 | public class LazyInitializationPattern { 2 | public static void main(String[] args) { 3 | Vehicle.getVehicleByTypeName(VehicleType.car); 4 | Vehicle.showAll(); 5 | Vehicle.getVehicleByTypeName(VehicleType.bus); 6 | Vehicle.showAll(); 7 | Vehicle.getVehicleByTypeName(VehicleType.car); 8 | Vehicle.showAll(); 9 | } 10 | } 11 | 12 | -------------------------------------------------------------------------------- /Creational/LazyInitialization/java/transactions-history/TransactionLogsDAO.java: -------------------------------------------------------------------------------- 1 | import java.util.Collection; 2 | 3 | public interface TransactionLogsDAO { 4 | 5 | Collection getHistory(Long clientId, int month, int year); 6 | } 7 | -------------------------------------------------------------------------------- /Creational/LazyInitialization/python/vehicle.py: -------------------------------------------------------------------------------- 1 | class Fruit: 2 | def __init__(self, item): 3 | self.item = item 4 | 5 | 6 | class Fruits: 7 | def __init__(self): 8 | self.items = {} 9 | 10 | def get_fruit(self, item): 11 | if item not in self.items: 12 | self.items[item] = Fruit(item) 13 | 14 | return self.items[item] 15 | 16 | 17 | if __name__ == '__main__': 18 | fruits = Fruits() 19 | print(fruits.get_fruit('Apple')) 20 | print(fruits.get_fruit('Lime')) -------------------------------------------------------------------------------- /Creational/Method Chaining/kotlin/main.kts: -------------------------------------------------------------------------------- 1 | class PersonBuilder { 2 | lateinit var firstName: String 3 | lateinit var lastName: String 4 | 5 | fun setFirstName(firstName: String) = apply { 6 | firstName = firstName 7 | } 8 | 9 | fun setLastName(lastName: String) = apply { 10 | lastName = lastName 11 | } 12 | 13 | fun build() = Person(firstName, lastName) 14 | } 15 | 16 | data class Person(val firstName: String, val lastName: String) 17 | 18 | val person = PersonBuilder() 19 | .setFirstName("John") 20 | .setLastName("Doe") 21 | .build() -------------------------------------------------------------------------------- /Creational/Method Chaining/perl/Rectangle.pm: -------------------------------------------------------------------------------- 1 | package Rectangle; 2 | 3 | # Constructor - default 0x0 rectangle 4 | sub new { 5 | my ($class, %args) = @_; 6 | 7 | my $self = { 8 | height => 0, 9 | width => 0 10 | }; 11 | 12 | return (bless($self, $class)); 13 | } 14 | 15 | # Width setter 16 | sub setWidth { 17 | my ($self, $width) = @_; 18 | 19 | $self->{width} = $width; 20 | return $self; 21 | } 22 | 23 | # Height setter 24 | sub setHeight { 25 | my ($self, $height) = @_; 26 | 27 | $self->{height} = $height; 28 | return $self; 29 | } 30 | 31 | 1; 32 | -------------------------------------------------------------------------------- /Creational/Method Chaining/perl/method_chaining.pl: -------------------------------------------------------------------------------- 1 | # Entry point for perl method chaining demo 2 | use strict; 3 | use warnings; 4 | 5 | use Rectangle; 6 | 7 | use Data::Dumper; 8 | $Data::Dumper::Terse = 1; 9 | 10 | my $rectangle = new Rectangle(); 11 | # display 0x0 rectangle 12 | print(Dumper($rectangle)); 13 | 14 | $rectangle->setWidth(5)->setHeight(10); 15 | # display 5x10 rectangle 16 | print(Dumper($rectangle)); 17 | -------------------------------------------------------------------------------- /Creational/Method Chaining/python/method_chaining.py: -------------------------------------------------------------------------------- 1 | class Rectangle: 2 | DEFAULT_WIDTH = 0 3 | DEFAULT_HEIGHT = 0 4 | 5 | def __init__(self): 6 | self.width = self.DEFAULT_WIDTH 7 | self.height = self.DEFAULT_HEIGHT 8 | 9 | def __str__(self): 10 | return "This is a "+str(self.width)+"x"+str(self.height)+" Rectangle" 11 | 12 | def set_width(self, width): 13 | self.width = width 14 | return self 15 | 16 | def set_height(self, height): 17 | self.height = height 18 | return self 19 | 20 | 21 | print(str(Rectangle())) 22 | #This is a 0x0 Rectangle 23 | print(str(Rectangle().set_width(5).set_height(10))) 24 | #This is a 5x10 Rectangle 25 | 26 | -------------------------------------------------------------------------------- /Creational/Method Chaining/ruby/method_chaining.rb: -------------------------------------------------------------------------------- 1 | class Rectangle 2 | DEFAULT_WIDTH = 0 3 | DEFAULT_HEIGHT = 0 4 | 5 | def initialize 6 | @width = DEFAULT_WIDTH 7 | @height = DEFAULT_HEIGHT 8 | end 9 | 10 | def to_s 11 | "This is a #{@width}x#{@height} Rectangle" 12 | end 13 | 14 | def set_width(width) 15 | @width = width 16 | self 17 | end 18 | 19 | def set_height(height) 20 | @height = height 21 | self 22 | end 23 | end 24 | 25 | puts Rectangle.new 26 | #=>This is a 0x0 Rectangle 27 | 28 | puts Rectangle.new.set_width(5).set_height(10) 29 | #=> This is a 5x10 Rectangle 30 | 31 | -------------------------------------------------------------------------------- /Creational/Module/README.md: -------------------------------------------------------------------------------- 1 | The Module Pattern is one of the most common design patterns used in JavaScript and for good reason. The module pattern is easy to use and creates encapsulation of our code. Modules are commonly used as singleton style objects where only one instance exists. The Module Pattern is great for services and testing/TDD. There are many different variations of the module pattern so for now I will be covering the basics and the Revealing Module Pattern in ES6. -------------------------------------------------------------------------------- /Creational/Multiton/README.md: -------------------------------------------------------------------------------- 1 | # Multiton Pattern 2 | 3 | > This pattern guarantees that there is only one instance per key within an application. 4 | 5 | The Multiton pattern is similar to the singleton pattern. It ensures that only one instance of an object is associated with a single key.
6 | This pattern simplifies the usage of globally shared objects in an application. Java's [ScriptEngineManager](https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngineManager.html) is an example implementation of the Multiton pattern. 7 | 8 | For more information, this [Wikipedia Article](https://en.wikipedia.org/wiki/Multiton_pattern) offers a good overview of the pattern. -------------------------------------------------------------------------------- /Creational/ObjectPool/java/Object.java: -------------------------------------------------------------------------------- 1 | public class Object{ 2 | public void Object(){ 3 | 4 | } 5 | } -------------------------------------------------------------------------------- /Creational/Prototype/README.md: -------------------------------------------------------------------------------- 1 | # The prototype design pattern 2 | 3 | The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. 4 | 5 | ![Prototype](https://sourcemaking.com/files/v2/content/patterns/Prototype.png) 6 | 7 | > The Factory knows how to find the correct Prototype, and each Product knows how to spawn new instances of itself. 8 | 9 | For more information about prototype design pattern: 10 | [Source making](https://sourcemaking.com/design_patterns/prototype) 11 | [Wikipedia Article](https://en.wikipedia.org/wiki/Factory_method_pattern) 12 | 13 | -------------------------------------------------------------------------------- /Creational/Prototype/java/Prototype.java: -------------------------------------------------------------------------------- 1 | interface Prototype { 2 | public Prototype getClone(); 3 | } -------------------------------------------------------------------------------- /Creational/Prototype/javascript/README.md: -------------------------------------------------------------------------------- 1 | The Prototype pattern utilizes [JavaScript's prototypical inheritance](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) to create objects. The prototype object acts as a blueprint for each object that it creates. These newly created objects are shallow clones of the original object. This pattern is very useful when creating objects in resource-intensive situations. -------------------------------------------------------------------------------- /Creational/SimpleFactory/java/CheesePizza.java: -------------------------------------------------------------------------------- 1 | 2 | public class CheesePizza implements Pizza { 3 | 4 | public void prepare() { 5 | System.out.println("Preparando a pizza de queijo"); 6 | } 7 | 8 | public void bake() { 9 | System.out.println("Assando a pizza de queijo"); 10 | } 11 | 12 | public void cut() { 13 | System.out.println("cortando a pizza de queijo"); 14 | } 15 | 16 | public void box() { 17 | System.out.println("embalando a pizza de queijo"); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Creational/SimpleFactory/java/ClamPizza.java: -------------------------------------------------------------------------------- 1 | 2 | public class ClamPizza implements Pizza { 3 | 4 | public void prepare() { 5 | System.out.println("Preparando a pizza de clam"); 6 | } 7 | 8 | public void bake() { 9 | System.out.println("Assando a pizza de clam"); 10 | } 11 | 12 | public void cut() { 13 | System.out.println("cortando a pizza de clam"); 14 | } 15 | 16 | public void box() { 17 | System.out.println("embalando a pizza de clam"); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Creational/SimpleFactory/java/PepperoniPizza.java: -------------------------------------------------------------------------------- 1 | 2 | public class PepperoniPizza implements Pizza { 3 | 4 | public void prepare() { 5 | System.out.println("Preparando a pizza de pepperoni"); 6 | } 7 | 8 | public void bake() { 9 | System.out.println("Assando a pizza de pepperoni"); 10 | } 11 | 12 | public void cut() { 13 | System.out.println("cortando a pizza de pepperoni"); 14 | } 15 | 16 | public void box() { 17 | System.out.println("embalando a pizza de pepperoni"); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Creational/SimpleFactory/java/Pizza.java: -------------------------------------------------------------------------------- 1 | 2 | public interface Pizza { 3 | void prepare(); 4 | void bake(); 5 | void cut(); 6 | void box(); 7 | } 8 | -------------------------------------------------------------------------------- /Creational/SimpleFactory/java/PizzaStore.java: -------------------------------------------------------------------------------- 1 | 2 | public class PizzaStore { 3 | 4 | public void orderPizza(String type) { 5 | Pizza pizza = SimplePizzaFactory.createPizza(type); 6 | pizza.prepare(); 7 | pizza.bake(); 8 | pizza.cut(); 9 | pizza.box(); 10 | 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Creational/SimpleFactory/java/SimplePizzaFactory.java: -------------------------------------------------------------------------------- 1 | 2 | public class SimplePizzaFactory { 3 | public static Pizza createPizza(String type) { 4 | Pizza pizza = null; 5 | if(type.equals("cheese")) { 6 | pizza = new CheesePizza(); 7 | } else if(type.equals("pepperoni")) { 8 | pizza = new PepperoniPizza(); 9 | } else if(type.equals("clam")) { 10 | pizza = new ClamPizza(); 11 | } else if(type.equals("veggie")) { 12 | pizza = new VeggiePizza(); 13 | } 14 | 15 | return pizza; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Creational/SimpleFactory/java/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | 2 | public class VeggiePizza implements Pizza { 3 | 4 | public void prepare() { 5 | System.out.println("Preparando a pizza de viggie"); 6 | } 7 | 8 | public void bake() { 9 | System.out.println("Assando a pizza de viggie"); 10 | } 11 | 12 | public void cut() { 13 | System.out.println("cortando a pizza de viggie"); 14 | } 15 | 16 | public void box() { 17 | System.out.println("embalando a pizza de viggie"); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Creational/SimpleFactory/java/readme.md: -------------------------------------------------------------------------------- 1 | # Simple FactorY 2 | 3 | Simple Factory Pattern is a Factory class in its simplest form (In comparison to Factory Method Pattern or Abstract Factory Pattern). In another way, we can say: In simple factory pattern, we have a factory class which has a method that returns different types of object based on given input. -------------------------------------------------------------------------------- /Creational/SimpleFactory/typescript/simple-factory.ts: -------------------------------------------------------------------------------- 1 | export namespace simpleFactoryExample { 2 | 3 | export class User { 4 | constructor(private _username: string, private _age: number) {} 5 | public get username(): string { return this._username } 6 | public get age(): number { return this._age } 7 | } 8 | 9 | abstract class UserFactory { 10 | public static create(username: string, age: number): User { 11 | return new User(username, age) 12 | } 13 | } 14 | 15 | const user: User = UserFactory.create('thalysonalexr', 23) 16 | console.log(user) 17 | } -------------------------------------------------------------------------------- /Creational/Singleton/cpp/SingletonDesignPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "SingletonDesignPattern.h" 3 | 4 | Singleton* Singleton::INSTANCE = NULL; 5 | 6 | Singleton::Singleton(){ } 7 | 8 | Singleton* Singleton::getInstance(){ 9 | if(INSTANCE == NULL) 10 | INSTANCE = new Singleton; 11 | return INSTANCE; 12 | } 13 | 14 | void Singleton::printSingleton(){ 15 | std::cout << "Singleton Class" << std::endl; 16 | } 17 | -------------------------------------------------------------------------------- /Creational/Singleton/cpp/SingletonDesignPattern.h: -------------------------------------------------------------------------------- 1 | #ifndef SINGLETONDESIGNPATTERN_H 2 | #define SINGLETONDESIGNPATTERN_H 3 | 4 | class Singleton { 5 | private: 6 | static Singleton* INSTANCE; 7 | Singleton(); 8 | public: 9 | static Singleton* getInstance(); 10 | void printSingleton(); 11 | }; 12 | 13 | #endif 14 | -------------------------------------------------------------------------------- /Creational/Singleton/cpp/main.cpp: -------------------------------------------------------------------------------- 1 | #include "SingletonDesignPattern.h" 2 | 3 | int main(){ 4 | Singleton* singleton = Singleton::getInstance(); 5 | singleton->printSingleton(); 6 | return 0; 7 | } 8 | -------------------------------------------------------------------------------- /Creational/Singleton/go/singleton.go: -------------------------------------------------------------------------------- 1 | package _go 2 | 3 | type single struct { 4 | O interface{} 5 | } 6 | 7 | var instantiated *single = nil 8 | 9 | func New() *single { 10 | if instantiated == nil { 11 | instantiated = new(single) 12 | } 13 | return instantiated 14 | } 15 | -------------------------------------------------------------------------------- /Creational/Singleton/golang/README.md: -------------------------------------------------------------------------------- 1 | # Singleton 2 | 3 | ## An Idiomatic Singleton Approach in Go 4 | 5 | We want to implement this Singleton pattern utilizing the Go idiomatic 6 | way of doing things. So we have to look at the excellent standard 7 | library packaged called sync. We can find the type Once. This object 8 | will perform an action exactly once and no more. 9 | 10 | ## Reference 11 | * [Singleton Pattern in Go](http://marcio.io/2015/07/singleton-pattern-in-go/) 12 | * [The singleton — object oriented design pattern in golang](https://medium.com/@MrToBe/the-singleton-object-oriented-design-pattern-in-golang-9f6ce75c21f7) 13 | -------------------------------------------------------------------------------- /Creational/Singleton/golang/Singleton.go: -------------------------------------------------------------------------------- 1 | // Singleton 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | "sync" 7 | ) 8 | 9 | type singleton struct { 10 | state string 11 | } 12 | 13 | var instance *singleton 14 | var once sync.Once 15 | 16 | func GetInstance() *singleton { 17 | once.Do(func() { 18 | instance = &singleton{} 19 | }) 20 | return instance 21 | } 22 | 23 | func (s *singleton) GetState() string { 24 | return s.state 25 | } 26 | 27 | func (s *singleton) SetState(state string) { 28 | s.state = state 29 | } 30 | 31 | func main() { 32 | var State = GetInstance() 33 | State.SetState("on") 34 | fmt.Println(State.state) 35 | var State2 = GetInstance() 36 | State2.SetState("off") 37 | fmt.Println(State.state) 38 | } 39 | -------------------------------------------------------------------------------- /Creational/Singleton/groovy/singleton.groovy: -------------------------------------------------------------------------------- 1 | @Singleton 2 | class singleton { 3 | int value 4 | 5 | static void main(String[] args) { 6 | singleton.instance 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Creational/Singleton/groovy/singletonLazyInitialisation.groovy: -------------------------------------------------------------------------------- 1 | @Singleton(lazy=true) 2 | class singleton { 3 | int value 4 | 5 | static void main(String[] args) { 6 | singleton.instance 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Creational/Singleton/java/SingletonDesignPattern.java: -------------------------------------------------------------------------------- 1 | public class SingletonDesignPattern { 2 | private static class Singleton { 3 | private static Singleton INSTANCE; 4 | 5 | private Singleton() { 6 | } 7 | 8 | public static Singleton getSingletonInstance() { 9 | if (INSTANCE == null) { 10 | INSTANCE = new Singleton(); 11 | } 12 | return INSTANCE; 13 | } 14 | 15 | public void printSingleton() { 16 | System.out.println("Singleton Class"); 17 | } 18 | } 19 | public static void main(String[] args) { 20 | Singleton singleton = Singleton.getSingletonInstance(); 21 | singleton.printSingleton(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Creational/Singleton/java/SingletonEager.java: -------------------------------------------------------------------------------- 1 | public class SingletonEager { 2 | private static SingletonEager instance = new SingletonEager(); 3 | 4 | private SingletonEager(){} 5 | 6 | public static SingletonEager getInstance() { 7 | return instance; 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Creational/Singleton/java/SingletonSimple.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | private static Singleton instance; 3 | 4 | private Singleton(){} 5 | 6 | public static Singleton getInstance() { 7 | if(instance == null) { 8 | instance = new Singleton(); 9 | } 10 | 11 | return instance; 12 | } 13 | } -------------------------------------------------------------------------------- /Creational/Singleton/java/SingletonSynchronizedBlock.java: -------------------------------------------------------------------------------- 1 | public class SingletonSynchronizedBlock { 2 | private static SingletonSynchronizedBlock instance; 3 | 4 | private SingletonSynchronizedBlock(){} 5 | 6 | public static SingletonSynchronizedBlock getInstance() { 7 | if(instance == null) { 8 | synchronized (SingletonSynchronizedBlock.class) { 9 | if(instance == null) { 10 | instance = new SingletonSynchronizedBlock(); 11 | } 12 | } 13 | } 14 | return instance; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Creational/Singleton/java/SingletonSynchronizedMethod.java: -------------------------------------------------------------------------------- 1 | public class SingletonSynchronizedMethod { 2 | private static SingletonSynchronizedMethod instance; 3 | 4 | private SingletonSynchronizedMethod(){} 5 | 6 | public static synchronized SingletonSynchronizedMethod getInstance() { 7 | if(instance == null) { 8 | instance = new SingletonSynchronizedMethod(); 9 | } 10 | return instance; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Creational/Singleton/kotlin/LazySingletonDesignPattern.kt: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Lazy initialization Singleton Pattern 4 | * 5 | * Thread safety with SYNCHRONIZED mode to ensure only one instance 6 | * will be created in race condition. 7 | */ 8 | fun main(args: Array) { 9 | DummySingleton.instance.print() 10 | } 11 | 12 | class Dummy { 13 | fun print() = println("Print Something!") 14 | } 15 | 16 | object DummySingleton { 17 | val instance: Dummy by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { 18 | Dummy() 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Creational/Singleton/kotlin/SingletonDesignPattern.kt: -------------------------------------------------------------------------------- 1 | object Singleton { 2 | var b: String? = null 3 | } 4 | 5 | fun main(args: Array) { 6 | Singleton.b = "foo" // is initialized at this point 7 | println(Singleton.b) // prints "foo" 8 | } -------------------------------------------------------------------------------- /Creational/Singleton/objective-c/Singleton.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | @interface Singleton : NSObject 4 | 5 | + (instancetype)sharedInstance; 6 | 7 | @end 8 | -------------------------------------------------------------------------------- /Creational/Singleton/python/singleton.py: -------------------------------------------------------------------------------- 1 | class Singleton(type): 2 | _instances = {} 3 | def __call__(cls, *args, **kwargs): 4 | if cls not in cls._instances: 5 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 6 | return cls._instances[cls] 7 | 8 | #Python2 9 | class MyClass(BaseClass): 10 | __metaclass__ = Singleton 11 | 12 | #Python3 13 | class MyClass(BaseClass, metaclass=Singleton): 14 | pass 15 | -------------------------------------------------------------------------------- /Creational/Singleton/ruby/README.md: -------------------------------------------------------------------------------- 1 | ## Running the example 2 | 3 | `ruby example.rb` 4 | 5 | Viewing the contents of the created `log.txt` should show 'Hello World!' followed by 'Hello 6 | World! (on a different call)' 7 | 8 | ## Use of the pattern 9 | 10 | When an object can and should only be instantiated once, like a Logger, the Singleton pattern 11 | makes a lot of sense. One object opens and writes to a file, rather than each method that 12 | wants to log having to open its own file. 13 | 14 | This pattern greatly simplifies the handling of globally available resources, but should not 15 | be used unless there is a specific reason for requiring only one instance of an object. 16 | -------------------------------------------------------------------------------- /Creational/Singleton/ruby/example.rb: -------------------------------------------------------------------------------- 1 | require_relative './logger.rb' 2 | 3 | Logger.instance.log('Hello World!') 4 | Logger.instance.log('Hello World! (on a different call)') 5 | -------------------------------------------------------------------------------- /Creational/Singleton/ruby/logger.rb: -------------------------------------------------------------------------------- 1 | class Logger 2 | def initialize 3 | @log = File.open('log.txt', 'a') 4 | end 5 | 6 | @@instance = Logger.new 7 | 8 | def self.instance 9 | @@instance 10 | end 11 | 12 | def log(msg) 13 | @log.puts(msg) 14 | end 15 | 16 | private_class_method :new 17 | end 18 | -------------------------------------------------------------------------------- /Creational/Singleton/scala/Singleton.scala: -------------------------------------------------------------------------------- 1 | // define the singleton 2 | object Singleton { 3 | var property: String = _ 4 | } 5 | 6 | // use this singleton 7 | object Main extends App { 8 | Console.println("Hello World: " + Singleton.property) 9 | Singleton.property = "THE BIG STRING" 10 | Console.println("Hello World: " + Singleton.property) 11 | } 12 | -------------------------------------------------------------------------------- /Creational/Singleton/scala/SingletonCounter.scala: -------------------------------------------------------------------------------- 1 | object SingletonCounter { 2 | 3 | private var currentCounterValue: Int = 0 4 | 5 | def add: Unit = { 6 | currentCounterValue = currentCounterValue + 1 7 | } 8 | 9 | def substract: Unit = { 10 | currentCounterValue = currentCounterValue - 1 11 | } 12 | 13 | def getCurrentCounterValue: Int = { 14 | currentCounterValue 15 | } 16 | } 17 | 18 | object Main extends App { 19 | println("Hello, world!") 20 | println(SingletonCounter.getCurrentCounterValue) 21 | SingletonCounter.add 22 | SingletonCounter.add 23 | println(SingletonCounter.getCurrentCounterValue) 24 | SingletonCounter.substract 25 | println(SingletonCounter.getCurrentCounterValue) 26 | } -------------------------------------------------------------------------------- /Creational/Singleton/swift/Singleton.swift: -------------------------------------------------------------------------------- 1 | class Singleton { 2 | 3 | // The singleton instance 4 | static let sharedInstance = Singleton() 5 | 6 | private init() { 7 | // Private init prevents creation of other instances 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /Creational/Singleton/typescript/singleton.ts: -------------------------------------------------------------------------------- 1 | export namespace SingletonPattern { 2 | class Singleton { 3 | private static instance: Singleton; 4 | 5 | constructor() { } 6 | 7 | static get Instance() { 8 | if (!this.instance) { 9 | this.instance = new Singleton(); 10 | } 11 | return this.instance; 12 | } 13 | } 14 | 15 | export function demo(): void { 16 | const s1 = Singleton.Instance; 17 | const s2 = Singleton.Instance; 18 | 19 | if (s1 === s2) { 20 | console.log("this is a singleton"); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Creational/Value Object/README.md: -------------------------------------------------------------------------------- 1 | # Value Object Pattern 2 | 3 | > The 'value objects' equality are not based on their identity... Two value objects are equals if they have the same value(s) and not if they are the same object. 4 | 5 | [Oracle defines some rules to create a value based object](https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html) 6 | 7 | 8 | [Wikipedia Article](https://en.wikipedia.org/wiki/Value_object) 9 | -------------------------------------------------------------------------------- /Creational/Value Object/kotlin/ValueObject.kt: -------------------------------------------------------------------------------- 1 | data class ValueObject(val firstValue: Int, val secondValue: Int) 2 | 3 | fun main(args: Array) { 4 | 5 | val v1 = ValueObject(1, 2) 6 | val v2 = ValueObject(1, 2) 7 | val v3 = ValueObject(2, 2) 8 | 9 | println("$v1 and $v2 is equal ${v1 == v2}") 10 | println("$v1 and $v3 is equal ${v1 == v3}") 11 | } -------------------------------------------------------------------------------- /FrontController/java/FrontControllerPatternDemo.java: -------------------------------------------------------------------------------- 1 | public class FrontControllerPatternDemo { 2 | public static void main(String[] args) { 3 | 4 | FrontController frontController = new FrontController(); 5 | //Go home 6 | frontController.dispatchRequest("Home"); 7 | 8 | //Go Tution 9 | frontController.dispatchRequest("Tution"); 10 | } 11 | } -------------------------------------------------------------------------------- /FrontController/java/GoHome.java: -------------------------------------------------------------------------------- 1 | public class GoHome { 2 | public void show(){ 3 | System.out.println("Welcome home dear!!"); 4 | } 5 | } -------------------------------------------------------------------------------- /FrontController/java/GoTution.java: -------------------------------------------------------------------------------- 1 | public class GoTution { 2 | public void show(){ 3 | System.out.println("Welcome to Tution"); 4 | } 5 | } -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Subject of the issue 2 | Describe your issue here. 3 | 4 | ### Your environment 5 | * version of angular-translate 6 | * version of angular 7 | * which browser and its version 8 | 9 | ### Steps to reproduce 10 | Tell us how to reproduce this issue. Please provide a working demo, you can use [this template](https://plnkr.co/edit/XorWgI?p=preview) as a base. 11 | 12 | ### Expected behaviour 13 | Tell us what should happen 14 | 15 | ### Actual behaviour 16 | Tell us what happens instead 17 | -------------------------------------------------------------------------------- /Miscellaneous/DAO/C#/DAO/Interfaces/MonsterDAO.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace DAO.Interfaces 6 | { 7 | interface MonsterDAO 8 | { 9 | List GetAllMonsters(); 10 | List GetMonstersByLevel(int level); 11 | Monster GetMonsterByName(string name); 12 | void SaveMonster(Monster monster); 13 | void DeleteMonsterByName(string name); 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Miscellaneous/DAO/C#/DAO/Monster.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace DAO 6 | { 7 | class Monster 8 | { 9 | public string Name { get; private set; } 10 | public int Level { get; private set; } 11 | public int HitPoints { get; private set; } 12 | public string Description { get; private set; } 13 | 14 | public Monster() { } 15 | 16 | public Monster(string name, int level, int hitPoints, string description) 17 | { 18 | Name = name; 19 | Level = level; 20 | HitPoints = hitPoints; 21 | Description = description; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Miscellaneous/DAO/java/BookDAO.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.List; 3 | 4 | public interface BookDAO { 5 | 6 | List getAllBooks(); 7 | Books getBookByIsbn(int isbn); 8 | void saveBook(Books book); 9 | void deleteBook(Books book); 10 | } -------------------------------------------------------------------------------- /Miscellaneous/DAO/java/DAO.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Miscellaneous/DAO/java/DAO.png -------------------------------------------------------------------------------- /Miscellaneous/DependencyInjection/C#/DependencyInjection/Concretes/AudioManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using DependencyInjection.Interfaces; 5 | 6 | namespace DependencyInjection.Concretes 7 | { 8 | class AudioManager : IAudioManager 9 | { 10 | public void PlaySound() 11 | { 12 | Console.WriteLine("I will play a sound - Doe Ray Me Far Sew La Tea Doe"); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Miscellaneous/DependencyInjection/C#/DependencyInjection/Concretes/GameManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using DependencyInjection.Interfaces; 5 | 6 | namespace DependencyInjection.Concretes 7 | { 8 | class GameManager 9 | { 10 | private readonly IAudioManager AudioManager; 11 | private readonly ISceneManager SceneManager; 12 | 13 | public GameManager(IAudioManager audioManager, ISceneManager sceneManager) 14 | { 15 | AudioManager = audioManager; 16 | SceneManager = sceneManager; 17 | } 18 | 19 | public void Tick() 20 | { 21 | AudioManager.PlaySound(); 22 | SceneManager.DisplayScene(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Miscellaneous/DependencyInjection/C#/DependencyInjection/Concretes/SceneManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using DependencyInjection.Interfaces; 5 | 6 | namespace DependencyInjection.Concretes 7 | { 8 | class SceneManager : ISceneManager 9 | { 10 | List Scenes = new List(); 11 | 12 | public void DisplayScene() 13 | { 14 | Console.WriteLine("I will display the Scene"); 15 | } 16 | 17 | public void ListScenes() 18 | { 19 | Scenes.ForEach(x => Console.WriteLine(x)); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Miscellaneous/DependencyInjection/C#/DependencyInjection/Interfaces/IAudioManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace DependencyInjection.Interfaces 6 | { 7 | interface IAudioManager 8 | { 9 | void PlaySound(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Miscellaneous/DependencyInjection/C#/DependencyInjection/Interfaces/ISceneManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace DependencyInjection.Interfaces 6 | { 7 | interface ISceneManager 8 | { 9 | void DisplayScene(); 10 | void ListScenes(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Miscellaneous/DependencyInjection/java/EmailService.java: -------------------------------------------------------------------------------- 1 | package com.journaldev.java.legacy; 2 | 3 | public class EmailService { 4 | 5 | public void sendEmail(String message, String receiver){ 6 | //logic to send email 7 | System.out.println("Email sent to "+receiver+ " with Message="+message); 8 | } 9 | } -------------------------------------------------------------------------------- /Miscellaneous/DependencyInjection/java/MyApplication.java: -------------------------------------------------------------------------------- 1 | package com.Miscellaneous.Dependency Injection.java.legacy; 2 | 3 | public class MyApplication { 4 | 5 | private EmailService email = null; 6 | 7 | public MyApplication(EmailService svc){ 8 | this.email=svc; 9 | } 10 | 11 | public void processMessages(String msg, String rec){ 12 | //do some msg validation, manipulation logic etc 13 | this.email.sendEmail(msg, rec); 14 | } 15 | } -------------------------------------------------------------------------------- /Miscellaneous/DependencyInjection/java/MyLegactTest.java: -------------------------------------------------------------------------------- 1 | package com.journaldev.java.legacy; 2 | 3 | public class MyLegacyTest { 4 | 5 | public static void main(String[] args) { 6 | MyApplication app = new MyApplication(); 7 | app.processMessages("Hi Pankaj", "pankaj@abc.com"); 8 | } 9 | 10 | } -------------------------------------------------------------------------------- /Miscellaneous/RulesEngine/C#/RulesEngine/CardUtilities/CardContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using RulesEngine.GameObjects; 5 | 6 | namespace RulesEngine.CardUtilities 7 | { 8 | class CardContext 9 | { 10 | public CardContext() { } 11 | public CardContext(BaseCard card, Player player) 12 | { 13 | Card = card; 14 | Player = player; 15 | } 16 | 17 | public BaseCard Card { get; set; } 18 | public Player Player { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Miscellaneous/RulesEngine/C#/RulesEngine/GameObjects/BaseCard.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace RulesEngine.GameObjects 6 | { 7 | enum CARD_TYPE 8 | { 9 | Monster, 10 | Item 11 | } 12 | 13 | abstract class BaseCard 14 | { 15 | public string Name { get; } 16 | 17 | public CARD_TYPE CardType { get; } 18 | 19 | public BaseCard( string name, CARD_TYPE card_type ) 20 | { 21 | Name = name; 22 | CardType = card_type; 23 | } 24 | 25 | public abstract void PlayCard(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Miscellaneous/RulesEngine/C#/RulesEngine/Interfaces/ICardRule.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using RulesEngine.CardUtilities; 5 | 6 | namespace RulesEngine.Interfaces 7 | { 8 | interface ICardRule 9 | { 10 | void Evaluate(CardContext ctx, out CardContext res); 11 | bool ShouldRun(CardContext ctx); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Miscellaneous/RulesEngine/C#/RulesEngine/Player.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace RulesEngine 6 | { 7 | class Player 8 | { 9 | public string Name { get; } 10 | public int HitPoints { get; } 11 | 12 | public Player(string name, int hitPoints) 13 | { 14 | Name = name; 15 | HitPoints = hitPoints; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Structural/Adapter/README.md: -------------------------------------------------------------------------------- 1 | # ADAPTER DESIGN PATTERN 2 | 3 | The adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code. 4 | 5 | An example is an adapter that converts the interface of a Document Object Model of an XML document into a tree structure that can be displayed. 6 | 7 | ![adapter visualization](https://upload.wikimedia.org/wikipedia/commons/e/e5/W3sDesign_Adapter_Design_Pattern_UML.jpg?1572053119677) -------------------------------------------------------------------------------- /Structural/Adapter/c#/IXmlToJson.cs: -------------------------------------------------------------------------------- 1 | namespace Adapter 2 | { 3 | public interface IXmlToJson 4 | { 5 | void ConvertXmlToJson(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Structural/Adapter/c#/JsonConverter.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Adapter 6 | { 7 | public class JsonConverter 8 | { 9 | private IEnumerable _manufacturers; 10 | 11 | public JsonConverter(IEnumerable manufacturers) 12 | { 13 | _manufacturers = manufacturers; 14 | } 15 | 16 | public void ConvertToJson() 17 | { 18 | var jsonManufacturers = JsonConvert.SerializeObject(_manufacturers, Formatting.Indented); 19 | 20 | Console.WriteLine("\nJSON list\n"); 21 | Console.WriteLine(jsonManufacturers); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Structural/Adapter/c#/Manufacturer.cs: -------------------------------------------------------------------------------- 1 | namespace Adapter 2 | { 3 | public class Manufacturer 4 | { 5 | public string Name { get; set; } 6 | public string Country { get; set; } 7 | public int Year { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /Structural/Adapter/c#/Program.cs: -------------------------------------------------------------------------------- 1 | namespace Adapter 2 | { 3 | class Program 4 | { 5 | static void Main(string[] args) 6 | { 7 | var xmlConverter = new XmlConverter(); 8 | var adapter = new XmlToJsonAdapter(xmlConverter); 9 | adapter.ConvertXmlToJson(); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Structural/Adapter/java/example1/Desktop.java: -------------------------------------------------------------------------------- 1 | public class Desktop implements Device { 2 | 3 | public void shutdown() { 4 | 5 | System.out.println("Shutdown for Desktop"); 6 | } 7 | 8 | public void boot() { 9 | 10 | System.out.println("Booting for Desktop"); 11 | } 12 | 13 | public void reboot() { 14 | 15 | System.out.println("Rebooting for Desktop"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Structural/Adapter/java/example1/Device.java: -------------------------------------------------------------------------------- 1 | public interface Device { 2 | 3 | public void shutdown(); 4 | public void boot(); 5 | public void reboot(); 6 | } 7 | -------------------------------------------------------------------------------- /Structural/Adapter/java/example1/Mobile.java: -------------------------------------------------------------------------------- 1 | 2 | public class Mobile { 3 | 4 | public void call() { 5 | 6 | System.out.println("Mobile makes calls"); 7 | } 8 | 9 | public void sms() { 10 | 11 | System.out.println("the mobile send Messages"); 12 | } 13 | 14 | public void boot(boolean auth) { 15 | 16 | if( auth ) { 17 | 18 | System.out.println("Mobile is booting"); 19 | } 20 | } 21 | 22 | public void restart() { 23 | 24 | System.out.println("mobile: restarting"); 25 | } 26 | 27 | public void turOff() { 28 | 29 | System.out.println("mobile is off"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Structural/Adapter/java/example1/Mobile.java~: -------------------------------------------------------------------------------- 1 | 2 | public class Mobile { 3 | 4 | public void call() { 5 | 6 | System.out.println("Mobile makes calls"); 7 | } 8 | 9 | public void sms() { 10 | 11 | System.out.println("the mobile send Messages"); 12 | } 13 | 14 | public void boot(boolean auth) { 15 | 16 | if( auth ) { 17 | 18 | System.out.println("Mobile is booting"); 19 | } 20 | } 21 | 22 | public void restart() { 23 | 24 | System.out.println("mobile: restarting"); 25 | } 26 | 27 | public void turOff() { 28 | 29 | System.out.println("mobile is off"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Structural/Adapter/java/example1/Notebook.java: -------------------------------------------------------------------------------- 1 | public class Notebook implements Device { 2 | 3 | public void shutdown() { 4 | 5 | System.out.println("Shutdown for Notebook"); 6 | } 7 | 8 | public void boot() { 9 | 10 | System.out.println("Booting for Notebook"); 11 | } 12 | 13 | public void reboot() { 14 | 15 | System.out.println("Rebooting for Notebook"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Structural/Bridge/java/BridgeDemo.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Created by trustgeek on 10/17/2017 {11:33 PM}. 4 | * Just like Adapter pattern, bridge design pattern is one of the Structural design pattern. 5 | * According to GoF bridge design pattern is: 6 | * Decouple an abstraction from its implementation so that the two can vary independently 7 | */ 8 | public class BridgeDemo { 9 | public static void main(String[] args) { 10 | Shape tri = new Triangle(new RedColor()); 11 | tri.applyColor(); 12 | 13 | Shape pent = new Pentagon(new GreenColor()); 14 | pent.applyColor(); 15 | } 16 | } -------------------------------------------------------------------------------- /Structural/Bridge/java/Color.java: -------------------------------------------------------------------------------- 1 | public interface Color { 2 | public void applyColor(); 3 | } 4 | -------------------------------------------------------------------------------- /Structural/Bridge/java/GreenColor.java: -------------------------------------------------------------------------------- 1 | public class GreenColor implements Color{ 2 | 3 | public void applyColor(){ 4 | System.out.println("green."); 5 | } 6 | } -------------------------------------------------------------------------------- /Structural/Bridge/java/Pentagon.java: -------------------------------------------------------------------------------- 1 | public class Pentagon extends Shape{ 2 | 3 | Pentagon(Color c) { 4 | super(c); 5 | } 6 | 7 | @Override 8 | public void applyColor() { 9 | System.out.print("Pentagon filled with color "); 10 | color.applyColor(); 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /Structural/Bridge/java/RedColor.java: -------------------------------------------------------------------------------- 1 | public class RedColor implements Color{ 2 | 3 | public void applyColor(){ 4 | System.out.println("red."); 5 | } 6 | } -------------------------------------------------------------------------------- /Structural/Bridge/java/Shape.java: -------------------------------------------------------------------------------- 1 | public abstract class Shape { 2 | //Composition - implementor 3 | Color color; 4 | 5 | //constructor with implementor as input argument 6 | Shape(Color c) { 7 | this.color = c; 8 | } 9 | 10 | abstract public void applyColor(); 11 | } 12 | -------------------------------------------------------------------------------- /Structural/Bridge/java/Triangle.java: -------------------------------------------------------------------------------- 1 | public class Triangle extends Shape{ 2 | 3 | Triangle(Color c) { 4 | super(c); 5 | } 6 | 7 | @Override 8 | public void applyColor() { 9 | System.out.print("Triangle filled with color "); 10 | color.applyColor(); 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /Structural/Builder/HowToUse.java: -------------------------------------------------------------------------------- 1 | public class HowToUse { 2 | private void testingUser() { 3 | 4 | /** 5 | * It will create object without validation of first name 6 | */ 7 | User user = new User.Builder() 8 | .setFirstName("Leonardo") 9 | .setLastName("da Vinci") 10 | .setAge(67) 11 | .make(); 12 | 13 | /** 14 | * It will create object with validation of first name 15 | */ 16 | User userNew = new User.Builder() 17 | .setFirstName("Leonardo") 18 | .setLastName("da Vinci") 19 | .setAge(67) 20 | .create(); 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /Structural/Composite/C#/1/Leaf.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CompositePattern 4 | { 5 | class Leaf : TreeComponent 6 | { 7 | private bool hasFallen; 8 | 9 | public void Fall() 10 | { 11 | if (hasFallen) 12 | { 13 | Console.WriteLine("Already fell from tree"); 14 | } 15 | else 16 | { 17 | Console.WriteLine("Falling from tree..."); 18 | hasFallen = true; 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Structural/Composite/C#/1/Tree.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace CompositePattern 4 | { 5 | class Tree : TreeComponent 6 | { 7 | public List Elements { get; private set; } 8 | 9 | public Tree() 10 | { 11 | Elements = new List(); 12 | } 13 | 14 | public void Fall() 15 | { 16 | foreach(TreeComponent c in Elements) 17 | { 18 | c.Fall(); 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Structural/Composite/C#/1/TreeComponent.cs: -------------------------------------------------------------------------------- 1 | namespace CompositePattern 2 | { 3 | interface TreeComponent 4 | { 5 | void Fall(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Structural/Composite/C#/2/IComponent.cs: -------------------------------------------------------------------------------- 1 | namespace Composite 2 | { 3 | public interface IComponent 4 | { 5 | int GetSize(); 6 | string Name { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Structural/Composite/java/CompositeDemo.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Created by trustgeek on 10/17/2017 {11:33 PM}. 4 | */ 5 | public class CompositeDemo { 6 | public static void main(String[] args) { 7 | 8 | 9 | } 10 | } -------------------------------------------------------------------------------- /Structural/Composite/java/Employee.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | 7 | package javaapplication10; 8 | 9 | /** 10 | * 11 | * @author Mohamed 12 | */ 13 | public interface Employee { 14 | 15 | public void add(Employee employee); 16 | public void remove(Employee employee); 17 | public Employee getChild(int i); 18 | public String getName(); 19 | public double getSalary(); 20 | public void print(); 21 | } 22 | -------------------------------------------------------------------------------- /Structural/Composite/java/employecompositedemo.java: -------------------------------------------------------------------------------- 1 | package javaapplication10; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | public class employecompositedemo { 8 | 9 | 10 | 11 | public static void main(String[] args) { 12 | Employee emp1=new Developer("per1", 10000); 13 | Employee emp2=new Developer("per2", 15000); 14 | Employee manager1=new Manager("per3",25000); 15 | manager1.add(emp1); 16 | manager1.add(emp2); 17 | Employee emp3=new Developer("per4", 20000); 18 | Manager generalManager=new Manager("per4", 50000); 19 | generalManager.add(emp3); 20 | generalManager.add(manager1); 21 | generalManager.print(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Structural/Decorator/README.md: -------------------------------------------------------------------------------- 1 | # Decorator 2 | 3 | The Decorator pattern allows you to attach new behaviours to an object at run time. This is done by wrapping the object to which you wish to add some behaviour inside a wrapper object containing that behaviour. -------------------------------------------------------------------------------- /Structural/Decorator/python/Readme.md: -------------------------------------------------------------------------------- 1 | ### How it works 2 | 3 | The Decorator pattern is used to dynamically add a new feature to an object without changing its implementation. 4 | 5 | It differs from inheritance because the new feature is added only to that particular object, not to the entire subclass. 6 | 7 | ### Usage 8 | 9 | In the wild, the Grok framework uses decorators to add functionalities to methods, like permissions. 10 | 11 | In the sample code, we add formatting options (boldface and italic) to a text by appending the corresponding tags ( and ). 12 | -------------------------------------------------------------------------------- /Structural/Decorator/typescript/decorator.ts: -------------------------------------------------------------------------------- 1 | let paint = (name: string, lastname: string) => { 2 | return `{name: '${name}', lastname: '${lastname}'}` 3 | } 4 | 5 | let decorativeFunction = (f: Function, name: string, lastname: string) => { 6 | let alreadyDecorated = () => { 7 | let ans = f(name, lastname) 8 | return ans.toUpperCase() 9 | } 10 | return alreadyDecorated 11 | } 12 | let decoratedFunction = decorativeFunction(paint, "Bruno", "Cardenas") 13 | console.log(decoratedFunction()) -------------------------------------------------------------------------------- /Structural/Facade/C#/Food.cs: -------------------------------------------------------------------------------- 1 | namespace FacadePattern 2 | { 3 | interface Food 4 | { 5 | void Order(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Structural/Facade/C#/Hamburger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FacadePattern 4 | { 5 | class Hamburger : Food 6 | { 7 | public void Order() 8 | { 9 | Console.WriteLine("Ordering a hamburger..."); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Structural/Facade/C#/Pizza.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FacadePattern 4 | { 5 | class Pizza : Food 6 | { 7 | public void Order() 8 | { 9 | Console.WriteLine("Ordering pizza..."); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Structural/Facade/C#/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FacadePattern 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | Waiter waiter = new Waiter(); 10 | 11 | waiter.OrderHamburger(); 12 | waiter.OrderPizza(); 13 | waiter.OrderSpaghetti(); 14 | 15 | Console.ReadLine(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Structural/Facade/C#/Spaghetti.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace FacadePattern 4 | { 5 | class Spaghetti : Food 6 | { 7 | public void Order() 8 | { 9 | Console.WriteLine("Ordering spaghetti..."); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Structural/Facade/C#/Waiter.cs: -------------------------------------------------------------------------------- 1 | namespace FacadePattern 2 | { 3 | class Waiter 4 | { 5 | private Food pizza; 6 | private Food spaghetti; 7 | private Food hamburger; 8 | 9 | public Waiter() 10 | { 11 | pizza = new Pizza(); 12 | spaghetti = new Spaghetti(); 13 | hamburger = new Hamburger(); 14 | } 15 | 16 | public void OrderPizza() 17 | { 18 | pizza.Order(); 19 | } 20 | 21 | public void OrderSpaghetti() 22 | { 23 | spaghetti.Order(); 24 | } 25 | 26 | public void OrderHamburger() 27 | { 28 | hamburger.Order(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Structural/Facade/README.md: -------------------------------------------------------------------------------- 1 | # FACADE DESIGN PATTERN 2 | 3 | > The facade (aka façade) design pattern hides the complexities of a system by providing a simple interface that can be used by a client to access a system 4 | 5 | By hiding the complexity of a system, this design pattern allows for a better code readability as well as reducing the dependencies 6 | of external code on the inner parts of a library, because the most part of the code uses the facade to access those inner parts. 7 | 8 | The facade design pattern uses the interface methods to delegate functions to the more complex methods that are part of the system 9 | implementation, which remain hidden for outside code (normally the client code). 10 | 11 | ## STRUCTURE 12 | 13 | Facade patterns 14 | -------------------------------------------------------------------------------- /Structural/Facade/java/Blackberry.java: -------------------------------------------------------------------------------- 1 | public class Blackberry implements MobileShop { 2 | 3 | @Override 4 | public void modelNo() { 5 | System.out.println(" Blackberry Z10 "); 6 | } 7 | 8 | @Override 9 | public void price() { 10 | System.out.println(" USD 1000.00 "); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Structural/Facade/java/Iphone.java: -------------------------------------------------------------------------------- 1 | public class Iphone implements MobileShop { 2 | 3 | @Override 4 | public void modelNo() { 5 | System.out.println(" Iphone 6 "); 6 | } 7 | 8 | @Override 9 | public void price() { 10 | System.out.println(" USD 2500.00 "); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Structural/Facade/java/MobileShop.java: -------------------------------------------------------------------------------- 1 | public interface MobileShop { 2 | public void modelNo(); 3 | 4 | public void price(); 5 | } 6 | -------------------------------------------------------------------------------- /Structural/Facade/java/Samsung.java: -------------------------------------------------------------------------------- 1 | public class Samsung implements MobileShop { 2 | @Override 3 | public void modelNo() { 4 | System.out.println(" Samsung galaxy tab 3 "); 5 | } 6 | 7 | @Override 8 | public void price() { 9 | System.out.println(" USD 1500.00 "); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Structural/Facade/java/ShopKeeper.java: -------------------------------------------------------------------------------- 1 | public class ShopKeeper { 2 | private MobileShop iphone; 3 | private MobileShop samsung; 4 | private MobileShop blackberry; 5 | 6 | public ShopKeeper() { 7 | iphone = new Iphone(); 8 | samsung = new Samsung(); 9 | blackberry = new Blackberry(); 10 | } 11 | 12 | public void iphoneSale() { 13 | iphone.modelNo(); 14 | iphone.price(); 15 | } 16 | 17 | public void samsungSale() { 18 | samsung.modelNo(); 19 | samsung.price(); 20 | } 21 | 22 | public void blackberrySale() { 23 | blackberry.modelNo(); 24 | blackberry.price(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Structural/Facade/kotlin/using facade design pattern for bank service.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Structural/Facade/kotlin/using facade design pattern for bank service.png -------------------------------------------------------------------------------- /Structural/Filter/java/AndCriteria.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public class AndCriteria implements Criteria { 4 | 5 | private Criteria firstCriteria; 6 | private Criteria secondCriteria; 7 | 8 | public AndCriteria(Criteria firstCriteria, Criteria secondCriteria) { 9 | this.firstCriteria = firstCriteria; 10 | this.secondCriteria = secondCriteria; 11 | } 12 | 13 | @Override 14 | public List meetCriteria(List persons) { 15 | return secondCriteria.meetCriteria(firstCriteria.meetCriteria(persons)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Structural/Filter/java/Criteria.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public interface Criteria { 4 | List meetCriteria(List persons); 5 | } 6 | -------------------------------------------------------------------------------- /Structural/Filter/java/CriteriaFemale.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class CriteriaFemale implements Criteria { 5 | @Override 6 | public List meetCriteria(List persons) { 7 | List femalePersons = new ArrayList<>(); 8 | for (Person person:persons) { 9 | if(person.getGender().equalsIgnoreCase("FEMALE")) { 10 | femalePersons.add(person); 11 | } 12 | } 13 | return femalePersons; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Structural/Filter/java/CriteriaMale.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class CriteriaMale implements Criteria { 5 | @Override 6 | public List meetCriteria(List persons) { 7 | List malePersons = new ArrayList<>(); 8 | for (Person person:persons) { 9 | if(person.getGender().equalsIgnoreCase("MALE")) { 10 | malePersons.add(person); 11 | } 12 | } 13 | return malePersons; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Structural/Filter/java/CriteriaSingle.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class CriteriaSingle implements Criteria { 5 | @Override 6 | public List meetCriteria(List persons) { 7 | List singlePersons = new ArrayList<>(); 8 | for (Person person:persons) { 9 | if(person.getMaritalStatus().equalsIgnoreCase("SINGLE")) { 10 | singlePersons.add(person); 11 | } 12 | } 13 | return singlePersons; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Structural/Filter/java/filter_pattern_uml_diagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/Structural/Filter/java/filter_pattern_uml_diagram.jpg -------------------------------------------------------------------------------- /Structural/Filter/java/readme.md: -------------------------------------------------------------------------------- 1 | Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects, using different criteria, chaining them in a decoupled way through logical operations. This type of design pattern comes under structural pattern as this pattern is combining multiple criteria to obtain single criteria. 2 | -------------------------------------------------------------------------------- /Structural/Flyweight/java/shape-circle-demo/Circle.java: -------------------------------------------------------------------------------- 1 | public class Circle implements Shape { 2 | private String color; 3 | private int x; 4 | private int y; 5 | private int radius; 6 | 7 | public Circle(String color){ 8 | this.color = color; 9 | } 10 | 11 | public void setX(int x) { 12 | this.x = x; 13 | } 14 | 15 | public void setY(int y) { 16 | this.y = y; 17 | } 18 | 19 | public void setRadius(int radius) { 20 | this.radius = radius; 21 | } 22 | 23 | @Override 24 | public void draw() { 25 | System.out.println("Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Structural/Flyweight/java/shape-circle-demo/README.md: -------------------------------------------------------------------------------- 1 | This simple demonstration describes Flyweight Design pattern by drawing 20 circles of different locations but it creates only 5 objects. 2 | Only 5 colors are available so color property is used to check already existing Circle objects. 3 | -------------------------------------------------------------------------------- /Structural/Flyweight/java/shape-circle-demo/Shape.java: -------------------------------------------------------------------------------- 1 | public interface Shape { 2 | void draw(); 3 | } 4 | -------------------------------------------------------------------------------- /Structural/Flyweight/java/shape-circle-demo/ShapeFactory.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class ShapeFactory { 4 | 5 | // Uncomment the compiler directive line and 6 | // javac *.java will compile properly. 7 | // @SuppressWarnings("unchecked") 8 | private static final HashMap circleMap = new HashMap(); 9 | 10 | public static Shape getCircle(String color) { 11 | Circle circle = (Circle)circleMap.get(color); 12 | 13 | if(circle == null) { 14 | circle = new Circle(color); 15 | circleMap.put(color, circle); 16 | System.out.println("Creating circle of color : " + color); 17 | } 18 | return circle; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Structural/PrivateClass/golang/car/car.go: -------------------------------------------------------------------------------- 1 | package car 2 | 3 | type Car struct { 4 | // Won't be exported (lowercase n) 5 | numWheels int 6 | // Will be exported (capital C) 7 | Color string 8 | } 9 | 10 | // Won't be able to be used outside of package 11 | type car struct {} 12 | -------------------------------------------------------------------------------- /Structural/PrivateClass/golang/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "./car" 4 | 5 | func main() { 6 | c := new(car.Car) 7 | c.Color 8 | 9 | // Will throw error 10 | c.numWheels 11 | // Will throw error 12 | c2 := new(car.car) 13 | } 14 | -------------------------------------------------------------------------------- /Structural/PrivateClass/kotlin/SalaryCalculator.kt: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal 2 | 3 | class SalaryCalculator(baseSalary: BigDecimal, bonuses: BigDecimal, overtime: BigDecimal) { 4 | 5 | private val salaryData: SalaryData 6 | 7 | val income: BigDecimal 8 | get() = salaryData.basePay.add(salaryData.bonuses.add(salaryData.overtime)) 9 | 10 | init { 11 | this.salaryData = SalaryData(baseSalary, bonuses, overtime) 12 | } 13 | 14 | internal inner class SalaryData(val basePay: BigDecimal, val bonuses: BigDecimal, val overtime: BigDecimal) 15 | } 16 | 17 | fun main(args: Array) { 18 | val salaryCalculator = SalaryCalculator(BigDecimal(1000), BigDecimal(100), BigDecimal(40)) 19 | println(salaryCalculator.income) 20 | } -------------------------------------------------------------------------------- /Structural/PrivateClass/python/Private_Class_Data.py: -------------------------------------------------------------------------------- 1 | class DataClass: 2 | """ 3 | Hide all the attributes. 4 | """ 5 | 6 | def __init__(self): 7 | self.value = None 8 | 9 | def __get__(self, instance, owner): 10 | return self.value 11 | 12 | def __set__(self, instance, value): 13 | if self.value is None: 14 | self.value = value 15 | 16 | 17 | class MainClass: 18 | """ 19 | Initialize data class through the data class's constructor. 20 | """ 21 | 22 | attribute = DataClass() 23 | 24 | def __init__(self, value): 25 | self.attribute = value 26 | 27 | 28 | def main(): 29 | m = MainClass(True) 30 | m.attribute = False 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /Structural/PrivateClass/readme.md: -------------------------------------------------------------------------------- 1 | # Private Class Data 2 | 3 | A class may expose its attributes (class variables) to manipulation when manipulation is no longer desirable, 4 | e.g. after construction. Using the private class data design pattern prevents that undesirable manipulation. 5 | A class may have one-time mutable attributes that cannot be declared final. 6 | Using this design pattern allows one-time setting of those class attributes. 7 | The motivation for this design pattern comes from the design goal of protecting class state by minimizing 8 | the visibility of its attributes (data). -------------------------------------------------------------------------------- /Structural/Proxy/README.md: -------------------------------------------------------------------------------- 1 | # Proxy Pattern 2 | 3 | > Allows for object level access control by acting as a pass through entity or a placeholder object. 4 | 5 | Proxy design pattern is mostly used to wrap some object in order to provide additional functionality while also maintaining the same signature and main functionality of the wrapped object. 6 | 7 | This pattern is useful when you need to limit access, add logging before and after each call or cache results of some object. 8 | 9 | For more information, Wikipedia provides a great overview of the pattern: [Wikipedia Article](https://en.wikipedia.org/wiki/Proxy_pattern) -------------------------------------------------------------------------------- /Structural/Proxy/java/AccessLimitingTextFile.java: -------------------------------------------------------------------------------- 1 | public class AccessLimitingTextFile implements TextFile { 2 | 3 | private static final String ADMIN_USER = "admin"; 4 | 5 | private final TextFile textFile; 6 | private final String user; 7 | 8 | public AccessLimitingTextFile(TextFile textFile, String user) { 9 | this.textFile = textFile; 10 | this.user = user; 11 | } 12 | 13 | @Override 14 | public String getContent() { 15 | if (ADMIN_USER.equals(user)) { 16 | return textFile.getContent(); 17 | } 18 | return "Must be " + ADMIN_USER + " to access the file"; 19 | } 20 | } -------------------------------------------------------------------------------- /Structural/Proxy/java/CachedTextFile.java: -------------------------------------------------------------------------------- 1 | public class CachedTextFile implements TextFile { 2 | 3 | private final TextFile textFile; 4 | private String content; 5 | 6 | public CachedTextFile(TextFile textFile) { 7 | this.textFile = textFile; 8 | } 9 | 10 | @Override 11 | public String getContent() { 12 | if (content == null) { 13 | content = textFile.getContent(); 14 | } 15 | return content; 16 | } 17 | } -------------------------------------------------------------------------------- /Structural/Proxy/java/RemoteTextFile.java: -------------------------------------------------------------------------------- 1 | public class RemoteTextFile implements TextFile { 2 | 3 | private final String content; 4 | 5 | public RemoteTextFile(String content) { 6 | this.content = content; 7 | } 8 | 9 | @Override 10 | public String getContent() { 11 | 12 | // Simulating a remotely hosted file. 13 | try { 14 | Thread.sleep(5000); 15 | } catch (InterruptedException ignored) { 16 | } 17 | return content; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Structural/Proxy/java/TextFile.java: -------------------------------------------------------------------------------- 1 | public interface TextFile { 2 | 3 | String getContent(); 4 | } -------------------------------------------------------------------------------- /Structural/Proxy/python/calculator.py: -------------------------------------------------------------------------------- 1 | #interface 2 | class ICalculator: 3 | def Add(): 4 | pass 5 | 6 | #subject 7 | class Calculator(ICalculator): 8 | def Add(self, First, Second): 9 | return First + Second 10 | 11 | #proxy 12 | class CalculatorProxy(ICalculator): 13 | 14 | def __init__(self): 15 | self.calculator = Calculator() 16 | 17 | def Add(self, First, Second): 18 | #method in base class automatically overriden 19 | print("Calculating...") 20 | result = str(First) + " + " + str(Second) + " = " + str(self.calculator.Add(First, Second)) 21 | return result 22 | 23 | #instance of proxy 24 | calc = CalculatorProxy() 25 | 26 | print(calc.Add(3,4)) 27 | -------------------------------------------------------------------------------- /Structural/Repository/csharp/ExampleEntitie.cs: -------------------------------------------------------------------------------- 1 | namespace Project.Repository.Entities 2 | { 3 | public class ExampleEntitie 4 | { 5 | public int Id { get; set; } 6 | public string Description { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /Structural/Repository/csharp/IDefaultRepository.cs: -------------------------------------------------------------------------------- 1 | using Project.Repository.Entities; 2 | using System.Collections.Generic; 3 | 4 | namespace Project.Repository.Interface 5 | { 6 | public interface IDefaultRepository 7 | { 8 | public void Remove(int id); 9 | public void Insert(ExampleEntitie obj); 10 | public List Get(); 11 | public ExampleEntitie Get(int id); 12 | public void Update(ExampleEntitie obj); 13 | } 14 | } -------------------------------------------------------------------------------- /Structural/Repository/csharp/UsingRepository.cs: -------------------------------------------------------------------------------- 1 | using Project.Repository.Entities; 2 | using Project.Repository.Interface; 3 | using System.Collections.Generic; 4 | 5 | namespace Project.Repository 6 | { 7 | public class UsingRepository 8 | { 9 | static void Main() 10 | { 11 | IDefaultRepository test = new ExampleRepository(); 12 | 13 | int id = 1; 14 | test.Remove(id); 15 | 16 | ExampleEntitie obj = new ExampleEntitie { Id = 1, Description = "Example" }; 17 | test.Insert(obj); 18 | 19 | List result = test.Get(); 20 | 21 | ExampleEntitie entitie = test.Get(obj.Id); 22 | 23 | test.Update(obj); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Structural/Repository/java/Product.java: -------------------------------------------------------------------------------- 1 | 2 | import java.math.BigDecimal; 3 | 4 | public class Product { 5 | 6 | private Integer id; 7 | private String cod; 8 | private String description; 9 | private BigDecimal value; 10 | 11 | public String getCod() { 12 | return cod; 13 | } 14 | public void setCod(String cod) { 15 | this.cod = cod; 16 | } 17 | public String getDescription() { 18 | return description; 19 | } 20 | public void setDescription(String description) { 21 | this.description = description; 22 | } 23 | public BigDecimal getValue() { 24 | return value; 25 | } 26 | public void setValue(BigDecimal value) { 27 | this.value = value; 28 | } 29 | public Integer getId() { 30 | return id; 31 | } 32 | public void setId(Integer id) { 33 | this.id = id; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Structural/Repository/java/ProductRepository.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public interface ProductRepository extends Repository { 4 | 5 | public List expiredProducts(); 6 | } 7 | -------------------------------------------------------------------------------- /Structural/Repository/java/ProductRepositoryDefault.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public class ProductRepositoryDefault extends RepositoryDefault implements ProductRepository { 4 | 5 | public List expiredProducts() { 6 | // TODO Auto-generated method stub 7 | return null; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Structural/Repository/java/Repository.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public interface Repository { 4 | 5 | public void add(T object); 6 | public void remove(int i); 7 | public List getAll(); 8 | public T getSpecific(int i); 9 | } -------------------------------------------------------------------------------- /Structural/Repository/java/RepositoryDefault.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public abstract class RepositoryDefault implements Repository { 5 | 6 | public void add(T object) { 7 | 8 | }; 9 | public void remove(int i) { 10 | 11 | }; 12 | public List getAll(){ 13 | 14 | return new ArrayList(); 15 | }; 16 | public T getSpecific(int i) { 17 | 18 | return null; 19 | }; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Structural/Repository/readme.md: -------------------------------------------------------------------------------- 1 | # Repository Pattern 2 | 3 | Definition 4 | 5 | ``` 6 | A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes 7 | 8 | ``` 9 | -------------------------------------------------------------------------------- /media/design-patterns.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/media/design-patterns.jpeg -------------------------------------------------------------------------------- /media/facade.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZoranPandovski/design-patterns/db0dcf0ceade1a84fc5466fc625a50cc1dd066fe/media/facade.png --------------------------------------------------------------------------------