Monday, February 13, 2012

More on Patterns - 1

Useful reminders for some useful patterns:

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

The Template Method Pattern ensures that the algorithm lives in only one place.

A hook is a method declared in the abstract class containing the template, but given an empty or default implementation. It can be used to help the subclasses to conditionally control the flow of the algorithm, or implement/skip an optional part of the algorithm.

A lot of people use this pattern, especially for making frameworks.

Factory Method is specialisation of Template Method

Strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and composition of objects uniformly.

Composite Pattern often used in UI design.

If the composite structure is complex or expensive to traverse, it may help to use caching.

There are trade-offs in implementing Composite: need to balance transparency and safety with your needs.

The State Pattern allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.

Strategy and State look very similar, but differ by intent. Think of Strategy Pattern as a flexible alternative to subclassing. You change the behaviour by composing with a different object. Think of State Pattern as an alternative to putting a lot of conditionals in your context. You can simply change the state object in the context to change its behaviour.

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

Remote Proxy controls access to remote objects (RMI), Virtual Proxy controls access to resources expensive to create (loading messages), and Protection Proxy controls access to resources based on access rights (Java dynamic proxy).

No comments: