Rob Vettor spoke on five patterns detailed in Design Patterns: Elements of Reusable Object-Oriented Software which is the book by the Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides) on 6/9/2012.
- Factory: This pattern tries to curtail having object instantiation sprinkled all over a code base which can be painful to change should the instantiation of the object be nontrivial. In Vettor's example, whenever one needed a distributor for strawberries, one would ask a factory that would instantiate the distributor. The decision as to the nature of the distributor would be facilitated by the factory based upon variables handed into a method call. The factory in his example would create either a Mexico or a California object which inherited from IDistributor and then hand the object back as an IDistributor.
- Strategy: As detailed by Josh Arnold here, this is a way to clean up messes that materialize in case statements or nested if/then/else logic gunk.
In this pattern each case in a case statement gets abstracted to its own class which inheirts a common interface. A context object gets the interface at a getsetter. In Rob Vettor's example, he made a duck quack... or scream... or bark depending on a differentiator.
His code:
var duck = new Duck();
var quackResult = duck.Quack();
duck.QuackStrategy =
QuackBehaviorFactory.SetQuackStrategy(QuackBehavior.Whisper);
quackResult = duck.Quack();
Here quackResult is an IQuackStrategy defined by a QuackBehavior differentiator at QuackBehaviorFactory which contains a case statement. The case statement is kept lean however. All of the real behavior is abstracted out to the IQuackStrategy children. - Observer: This pattern has to do with listening for events!
- Decorator: Extends an existing object by adding state to it at runtime. In his example, Lamborghni subclasses Car and the constructor for Lamborghni sets the price getsetter on Car to something Lamborghni appropriate. The price may climb as we add options like so (where "car" is an existing variable of type Lamborghni):
car = new OptionalLeather(car);
Yay! - Template Method: This is for algorithms. One holds most algorithmic logic in a parent while deferring sections to child classes. Mr. Vettor's example was of lotteries which may differ in number generation from state to state.
Note that at var quackResult = duck.Quack(); above before QuackBehaviorFactory is called, that quackResult will be null. QuackBehaviorFactory will need occasional surgical updating so this pattern does break with O/CP somewhat.
No comments:
Post a Comment