{"id":23058906,"url":"https://github.com/olavomoreirap/design-pattern-strategy","last_synced_at":"2026-01-18T06:51:26.047Z","repository":{"id":267325889,"uuid":"899670322","full_name":"zenonxd/design-pattern-strategy","owner":"zenonxd","description":"Encapsulates interchangeable algorithms, promoting modularity and extensibility while adhering to clean coding principles.","archived":false,"fork":false,"pushed_at":"2024-12-09T17:17:41.000Z","size":172,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-08T20:15:18.708Z","etag":null,"topics":["design-pattern-java","design-pattern-strategy","design-patterns","strategy"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zenonxd.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-06T18:52:49.000Z","updated_at":"2024-12-09T18:44:17.000Z","dependencies_parsed_at":"2024-12-09T18:27:24.777Z","dependency_job_id":"07323d64-ee48-4179-8c3e-4869651c2e46","html_url":"https://github.com/zenonxd/design-pattern-strategy","commit_stats":null,"previous_names":["zenonxd/design-pattern-strategy"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zenonxd%2Fdesign-pattern-strategy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zenonxd%2Fdesign-pattern-strategy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zenonxd%2Fdesign-pattern-strategy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zenonxd%2Fdesign-pattern-strategy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zenonxd","download_url":"https://codeload.github.com/zenonxd/design-pattern-strategy/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246944976,"owners_count":20858872,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["design-pattern-java","design-pattern-strategy","design-patterns","strategy"],"created_at":"2024-12-16T02:18:20.024Z","updated_at":"2026-01-18T06:51:25.982Z","avatar_url":"https://github.com/zenonxd.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# About\n\nBrief study about Design Pattern Strategy with Java.\n\n# How does it work?\n\nBasically, we can define a common interface for a group of \"behaviors\" that are related.\n\nEach implementation from this interface will represent a \"strategy\", and the client can choose which strategy to use.\n\nIn this study we are going to see the implementation of this strategy in an if-else code, but that's not the unique\nuse of this pattern, check it out:\n\n## Where strategy is useful beyond if-else?\n\nHere are some situations:\n\n### Configurable systems\n\nWhen we need to offer different ways to execute an action, like: \n\n1. Calculate discounts;\n2. Process payment;\n3. Determine some validation policy.\n\nPut some code with example.\n\n### Polymorphism behavior\n\nWhen different objects of a hierarchy needs to implement similar behaviors with variations (WITHOUT USING HIERARCHY).\n\n(Write more).\n\nPut some code with example.\n\n### Modular processing\n\nWhen different steps of the processing can be altered or combined dynamically.\n\n(Write more).\n\nPut some code with example.\n\n### Complex conditional logic\n\nReplace if-else, making it easier to add new conditions without the need to change the existent code.\n\n(Write more).\n\nPut some code with example.\n\n### Testability\n\nMaking it easier for unitary tests, isolating and testing each behavior individually\n\n(Write more).\n\nPut some code with example.\n\n\n# If-else (service) - example\n\n![img.png](img.png)\n\nThis, is going to become this:\n\n![img_1.png](img_1.png)\n\n[Refactoring Guru Strategy Java](https://refactoring.guru/pt-br/design-patterns/strategy/java/example)\n\n## Identifying the problem (Patterns)\n\nThe first thing we need to see to know if we need to use this pattern, is if we have a lot of conditionals and depending\non the outcomes, the result are the same.\n\nFor example: we need to make a payment, right? If we are going to use a credit card is one system, a debit card is another \none, pix other service as well.\n\nThe implementation of each payment WILL BE different but the purpose is the same, MAKE A PAYMENT.\n\nIn our example is a similar concept, we are going to send a notification to different social networks.\n\nSo, lets begin!\n\n## Creating the interface\n\nWe are going to create an interface. The names as always is what we intend to do + Strategy. Since we want to send\nnotifications, we are going to use ``NotificationStrategy``.\n\nEach implementation of this interface will be a **DIFFERENT STRATEGY**, but every strategy will need common attributes.\n\n```java\npublic interface NotificationStrategy {\n    \n    void sendNotification(String destination, String message);\n}\n```\n\nOk, we created the strategy interface, now we need to create **each strategy**! We can create inside the service package,\nanother one called ``strategy``, and inside this package we can create each one of them.\n\nFor example, if we have a notification type that's going to be sended by an email, we create a java class ``Email\nNotificationStrategy`` that's going to implement our interface. We can see in the image above that we have: Discord,\nTwitter and Instagram notifications as well, so we do the same thing.\n\nWe can remove the \"if\" conditions inside the service and insert inside the method on each Java class.\n\nNow, to use everything inside the service (and method), we need to create a \"context\", indicating from witch parameter\neach strategy will be used, we are going to use ``Map\u003cKey, Value\u003e``. The key will be the channel (instagram, twitter or\ndiscord, for example) and the Value will be the implementation, check it out:\n\n```java\nimport java.util.Map;\n\npublic class NotificationService {\n\n\n    private final Map\u003cString, NotificationStrategy\u003e mapStrategy = Map.of(\n            \"discord\", new DiscordNotificationStrategy(),\n            \"instagram\", new InstagramNotificationStrategy(),\n            \"twitter\", new TwitterNotificationStrategy(),\n            \"email\", new EmailNotificationStrategy(),\n            \"whatsapp\", new WhatsappNotificationStrategy()\n    );\n    \n    public void notify(String channel, String destination, String message) {\n        \n        //.get gets the key and by that we can use the method sendNotification, passing the\n        //destination and the message\n        mapStrategy.get(channel).sendNotification(destination, message);\n    }\n}\n```\n\nNow, if we go to postman, and make a POST passing the channel \"instagram/whatsapp/email/discord\" it'll work perfectly.\n\nThis was a simple method, but it could be a complex one as well, like calling the instagram/whatsapp API.\n\n\n\n\n\n\n\n# Advantages\n\nWith this implementation, we could insert new strategies inside the Map, without the need to create a huge code inside\nthe service.\n\nFurthermore, this method makes it easier to make unitary tests inside the application.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Folavomoreirap%2Fdesign-pattern-strategy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Folavomoreirap%2Fdesign-pattern-strategy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Folavomoreirap%2Fdesign-pattern-strategy/lists"}