Sunday, April 29, 2012

Make everything look pretty!

Lets learn a new pattern! This new pattern is all about decorations. Well, that't not completely true. The decorator pattern is used to add more functionality to a class. It could be used to create a new decoration that a user may see, or it may be more in the background. There are 2 examples I want to entertain, but we will get to those later. First lets learn how to use it. Start with the class that you want to decorate. Say you have a set up players in a game. One of the most useful items in a RPG is the ability to use potions or other items that will either increase or decrease a stat for a short period of time. You extend this class with your decorator. This decorator is then extended further to classes that represent the separate decorations. These decorations will either add to and or modify current methods. For example, with your players, you probably have an attack speed or a movement speed (these may or may not be reliant on the same speed value). If there was a decorator of, say, Potions. One potion may be used to increase the speed value. Now that particular player gets a speed boost. You can make this call by calling the speedboost potion method as such: if you have a player King and you want him to walk faster. He has a speed method that returns the speed value. To make him use the potion you call a similar line to: King = new speedBoost(King.speed());

The other example is one that is more visible to the user. It is the same one that is used in the book for this class. It involves coffee, the decorator pattern will change the cost and description of a drink depending on the additions made to it, be it chocolate, caramel, etc.

No comments:

Post a Comment