Thursday, July 9, 2020

Advantages of Strategy Design Pattern

Advantages of Strategy Design Pattern Design Pattern Exposed: Strategy Pattern Back Home Categories Online Courses Mock Interviews Webinars NEW Community Write for Us Categories Artificial Intelligence AI vs Machine Learning vs Deep LearningMachine Learning AlgorithmsArtificial Intelligence TutorialWhat is Deep LearningDeep Learning TutorialInstall TensorFlowDeep Learning with PythonBackpropagationTensorFlow TutorialConvolutional Neural Network TutorialVIEW ALL BI and Visualization What is TableauTableau TutorialTableau Interview QuestionsWhat is InformaticaInformatica Interview QuestionsPower BI TutorialPower BI Interview QuestionsOLTP vs OLAPQlikView TutorialAdvanced Excel Formulas TutorialVIEW ALL Big Data What is HadoopHadoop ArchitectureHadoop TutorialHadoop Interview QuestionsHadoop EcosystemData Science vs Big Data vs Data AnalyticsWhat is Big DataMapReduce TutorialPig TutorialSpark TutorialSpark Interview QuestionsBig Data TutorialHive TutorialVIEW ALL Blockchain Blockchain TutorialWhat is BlockchainHyperledger FabricWhat Is EthereumEthereum TutorialB lockchain ApplicationsSolidity TutorialBlockchain ProgrammingHow Blockchain WorksVIEW ALL Cloud Computing What is AWSAWS TutorialAWS CertificationAzure Interview QuestionsAzure TutorialWhat Is Cloud ComputingWhat Is SalesforceIoT TutorialSalesforce TutorialSalesforce Interview QuestionsVIEW ALL Cyber Security Cloud SecurityWhat is CryptographyNmap TutorialSQL Injection AttacksHow To Install Kali LinuxHow to become an Ethical Hacker?Footprinting in Ethical HackingNetwork Scanning for Ethical HackingARP SpoofingApplication SecurityVIEW ALL Data Science Python Pandas TutorialWhat is Machine LearningMachine Learning TutorialMachine Learning ProjectsMachine Learning Interview QuestionsWhat Is Data ScienceSAS TutorialR TutorialData Science ProjectsHow to become a data scientistData Science Interview QuestionsData Scientist SalaryVIEW ALL Data Warehousing and ETL What is Data WarehouseDimension Table in Data WarehousingData Warehousing Interview QuestionsData warehouse architectureTalend T utorialTalend ETL ToolTalend Interview QuestionsFact Table and its TypesInformatica TransformationsInformatica TutorialVIEW ALL Databases What is MySQLMySQL Data TypesSQL JoinsSQL Data TypesWhat is MongoDBMongoDB Interview QuestionsMySQL TutorialSQL Interview QuestionsSQL CommandsMySQL Interview QuestionsVIEW ALL DevOps What is DevOpsDevOps vs AgileDevOps ToolsDevOps TutorialHow To Become A DevOps EngineerDevOps Interview QuestionsWhat Is DockerDocker TutorialDocker Interview QuestionsWhat Is ChefWhat Is KubernetesKubernetes TutorialVIEW ALL Front End Web Development What is JavaScript รข€" All You Need To Know About JavaScriptJavaScript TutorialJavaScript Interview QuestionsJavaScript FrameworksAngular TutorialAngular Interview QuestionsWhat is REST API?React TutorialReact vs AngularjQuery TutorialNode TutorialReact Interview QuestionsVIEW ALL Mobile Development Android TutorialAndroid Interview QuestionsAndroid ArchitectureAndroid SQLite DatabaseProgramming ArchitectureDesign Patt ern Exposed: Strate... Design Patterns (8 Blogs) Become a Certified Professional Design Pattern Exposed: Strategy Pattern Last updated on May 22,2019 6.5K Views vinayak k6 Comments Bookmark Become a Certified Professional Welcome to the first post of Design Patterns Exposed series. In this series we are going to uncover each Design Pattern from scratch.Simply knowing a programming language and its constructs will not make you a better programmer or developer. It requires knowledge of Design Patterns to create software that will work today and also in future.Many developers have already come across those design problems that you are facing right now or will face in the future. They have specified a standard way of dealing with that problem. So by using Design Patterns you get the advantage of using proven techniques.Each Design Pattern is for solving a particular kind of situation; there might be situations where more than one Design Pattern can be used.Most of the programmers just try to solve the problem they face without bothering about design patterns, redundant code or even tight-coupling. But good programmers start differently. They think about todays requirements, future requirements, maintenance of code and re-usability of code.Good programmers are not in a hurry to start coding once they get the requirements. They sit and think about the problem; about whether their design will work. If yes, whether it will work after 6 months, when requirements will change.Good programmers take their pen and paper and start designing their classes and relationship between classes. They try to get loose coupling and high cohesion in their design, while doing all these they have Object-Oriented Principles in their mind. They dont go inside low-level code immediately. To design flexible and reusable software, you should follow this approach; otherwise you will always find yourself modifying code that you had written earlier.There is only one thing that is constant in software industry and that is Change. The requirements will certainly keep changing. So how do we design the software that your code can easily adapt to future requirements? For that you have to start early, and design it in such a way that future requirements doesnt break your previous code.How Can I do that?Well, it can be done by following Design Principles and Design Patterns based on those principles.Now, lets dive into coding and get started on the journey to become a better programmer. In this post, we are going to uncover one of the most important pattern Strategy Pattern.When I say the most important it reflects on the common problem that is solved by Strategy Pattern.What is Strategy Pattern?Here is the definition straight from the Gang of Four book: The Strategy Pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time. In case you are not able to understand, dont worry, we are going to explain it in a sim pler way for you to understand.Lets first understand the problem and then we will see how Strategy Pattern can solve that.In the above UML diagram, we have Animal abstract class and two concrete classes, Dog and Bird, extending from Animal super class.So lets define an Animal abstract class and two concrete classes, Dog and Bird.What you think about the above design? There is one big mistake in our design.All the animals cannot fly, like in the above case a dog cannot fly. But still it has fly behavior.We made a mistake by writing the abstract fly () method inside Animal class. This design will force each sub-class Dog, Bird, Penguin, Crocodile, Goose etc. to implement fly () method.We should have understood that flying is an ability that not all animals will have. By providing fly () method in Animal abstract class we have set the flying ability in all sub-classes which is not correct for all sub-classes of animals.You might think whats the problem in implementing the fly method in the sub-classes. Although you can implement the fly () method in the non-flying Animal sub-classes to just print I cant fly. But the problem is, you are still giving the fly behavior to non-flying animals. This is not correct.How does it feel to call dog.fly () or crocodile.fly () .So, now we have understood that our design is not correct and we should remove the fly () method from the Animal sub-class.What is the other way of designing our classes in a way that our design do not enforce all Animal sub-classes to have fly behavior.One solution that immediately comes to mind is that we can make a flying interface having fly method and only animals that can fly will implement that flying interface. This way we will not enforce all Animal sub-classes to define a fly behavior. So lets code this design approach.Now, our Animal class will look like the below code after removing the fly method from the Animal class.Now lets define the Flying interfaceNow, Dog class will be changed as the code below and it does not need to have fly behavior.Lets see some of our Animal sub-classes that will have flying behavior. We have solved our previous problem, but we got into a new trouble and that is Code Duplication.Say, we are going to have 100 different flying Animal sub-classes. We have to duplicate the code for fly behavior since flying interface cannot provide any implementation for fly behavior, and later if we want to change the fly () method implementation in any sub-class we will have to open that class and change the code, which is bad. We are lacking something big and, that is, we cannot change the flying behavior of a class at run-time.But dont worry, Strategy Pattern is there to get you out of this problem.So lets refactor our code to use Strategy Pattern.Flying interface will remain the same as it is. Now, rather than each flying sub-class implementing the flying interface itself, we are going to define separate concrete classes that will implement different flyin g behavior. Lets see how to do that.So, how it all works,lets see the TestClassBy using Strategy Pattern we are now able to change the flying behavior of any animal at run-time and that is without enforcing any sub-classes to specify the flying behavior itself.When to use Strategy Pattern?When you want to be able to change the behavior at run-time dynamically.To make sure you clearly understand the Strategy Pattern lets take another example. In the above Employee class we are setting the pay of the employee depending on his/her designation. If an employee is an Intern we are adding 10% bonus in the basic salary to calculate the actual pay.If an employee is a Web Developer we are adding 20% bonus in the basic salary to calculate the actual pay and the similar process follows for other types of employees. Although our algorithm for calculating the actual pay is very simple to make it easier to understand but most of the time, it includes many comparisons and calculations.So, whats wro ng with employee-class code ?Well, the code for calculating pay (getPay() ) is static. Suppose I want to change the bonus for Intern from 10% to 14%. I will have to open the Employee-class code and change it.And another problem is I cannot change an employees pay algorithm at run-time. So, how to do that? Strategy Pattern is specifically used for handling this kind of problem.Lets refactor the code to use Strategy Pattern.I am going to define several algorithms to calculate pay. Then I will be able to use any of these algorithms to calculate pay at run-time.Now, lets see how Employee class is going to change.Note: I have removed the pay calculation logic from Employee class and created a set PayAlgorithm () method through which I will set the PayAlgorithm that I want to use for pay calculation.This will give me the flexibility to calculate the pay by specifying any PayAlgorithm dynamically at run-time. Also, note that later if I have to change the pay calculation logic I can create a new PayAlgorithm and use that to calculate the pay. I dont need to change the previous code, isnt it great?So lets see it working.I hope you understood the Strategy Pattern very well. The best way to learn something is by practicing.In case you have any queries relating to Strategy Pattern or any other Pattern, leave your queries below.Watch out for the next post, where we will uncover one of the most popular Design Pattern, Factory Pattern.Till then you can download the code; play with it and make sure you cement the Strategy Pattern in your head.Got a question for us? Mention them in the comments section and we will get back to you.Related Posts:Get started with Design patternsRecommended videos for you Design Patterns: Solution to Software Design Problems Watch Now Design Patterns : Tailor Made Solutions for Software Development Watch Now Design Patterns : The Ultimate Blueprint for Software Watch Now Design Patterns : The Ultimate Blueprint for Software-I Watch Now Design Patt erns:Tailor-made Solutions for Software Development Watch NowRecommended blogs for you Design Pattern Exposed: Strategy Pattern Read Article TOGAF Standard 9.2 : A Complete Guide Read Article Design Pattern Exposed: Factory Pattern Read Article Important Java Design Patterns You Need to Know About Read Article Comments 6 Comments Trending Courses in Systems Architecture Design Patterns Certification Training3k Enrolled LearnersWeekend/WeekdaySelf Paced Reviews 5 (1100)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.