This little how-to will teach all you programing proteges the methods that us Grandmaster Programers use. For our first topic of business is the Strategy Pattern. It "defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy let the algorithm vary independently form clients that use it." If you completely understand what that means, great! For those of you whom have no idea what I just said, let me break it down for you.
The idea is to break-up your code so that you don't have to have many copies of your code. This will not only speed up your program but also conserve space. Some will say that inheritance is the way to do this but I disagree. Interfacing is much more efficient. So, what does all of this mean? Here is a step by step:
- Break up your code into groups
This allows you to look at what you have and what you need to do. Break up the code to the point where you can see an outline of what actions each class has. - Create interfaces
Now that you have a list of the actions you classes have, put the common methods together. For instance, if you have a group of duck classes, take out all the methods that have to do with flying and put them into a generic interface that lists all the possible ways to fly - Declare the interface
Now in your main superclass declare the interfaces. ie. if you have an interface called FlyBehavior, in your superclass, add the line "FlyBehavior flyBehavior;" - Use the methods
Now in your superclass you can call the flyBehavior and call the appropriate method that your subclass needs. ie. Your interface has a method called FlyWithWings. Make a public void performFly() and call the fly with wings method: flyBehavior.FlyWithWings(); - Tell your subclass to fly
Now in your subclass create the ability to fly (flyBehavior = new FlyWithWings();). now when you call the performFly() your duck will now fly!
Now, go out and Program like a Grandmaster!
No comments:
Post a Comment