Archive

Posts Tagged ‘design patterns’

Visitor Design Pattern

January 9th, 2011 No comments

Visitor Design Pattern

Problem

Sometimes we have multiple operations that need to be implemented on a structure of objects. Traditionally we would implement each of the objects to derive of a base class with each of the operations, and then override the operations to implement them. This can be a problem if the operations are different in nature, as well as if the number of operations exceeds the number of different subclasses in the tree. How can we overcome this problem?

Solution

The solution is the visitor pattern. The visitor pattern has each object class in the structure only has one method called AcceptVisitor() which takes a visitor class as a parameter. A visitor is an implementation of a particular operation, and has methods for each of the class types in the structure. The object in the structure calls its appropriate method on the visitor. For example, if a tree structure contained two types of classes, Foo and Fib. Then when we wanted to perform a function on them we pass down a visitor that implements the function, and nodes of type Foo call the VisitedFoo() function on the visitor, which implements the function for objects of type Foo

Consequences

It is easy to add operations, simply derive anew visitor class.

However, it is hard to add new class types to the structure, since you need to change both the base class and all subclasses of the visitors for the change.

Example of visitor design pattern

Chain of Responsibility Design Pattern

January 9th, 2011 No comments

Chain of Responsibility Design Pattern

Problem

Consider the case where you have a structural hierarchy of object that is not necessarily subclasses from the same base class. Now lets say there is a piece of functionality that they all can implement, but it is not statically determinate which should handle the case. Now I know that sounds a little complicated, but picture a context sensitive help system. Each piece of the display may have a piece of text that is wants to display when ever the cursor is over top of it, or it may not. In the case where a piece doesn’t want to handle it, you want the class that contains it to display a more general help string. You also want this system to be dynamic at run-time. How can this be done?

Solution

The Chain of responsibility can solve this problem. The chain of responsibility requires that each of the classes involved inherit from a base class, let’s say HelpHandler. Now when they are instantiated, the objects all initialize their parent class with a successor, which is a reference to another object that is also derived from the base class. When the time comes to call the method that you want to pass up the chain, the first object picked is the most appropriate one. If the object doesn’t want (or can’t handle) the request, it calls the BaseClass::Method() which calls the method for the successor, and so on, until one of the objects handles the request.

Consequences

The chain of responsibility makes it so the client doesn’t need know who is in fact handling the request, only that the request is being handled. As well, you can change the hierarchy at run-time to provide for a changing environment. However, it should be noted that in this system all participants in the chain could refuse to handle the request, and the client would not know.

Command Design Pattern

January 9th, 2011 No comments

Problem

How can we issue request to other objects in a system, without having to know who will receive the request, or even what the request is? This can be useful for implementing functionality such as a menu system, where each menu item has a command that it executes, but it doesn’t want to know what it is, it only needs to trigger the command at the right time. How can this be done?

Solution

The command pattern is simple the use of objects as commands in a system. The command class has a virtual member called Execute(). In our above example, the menu item could take a command object as an initialization parameter, and when the application runs, then menu item gets a command, the when the menu item is clicked it calls Execute() on the command.

Consequences

Commands are very powerful, and can support a lot of different functionality. For example, if the command registered itself with some global undo class when it executes, then simply by reversing each command in reverse order (I smell a stack…) we can undo any sequence of commands provided every command class can be undone. Command object separates the object that triggers an operation from the one that executes the operation. By using the Composite pattern you can extend a command to execute multiple commands. And since all commands derive from the command base class, adding new commands is easy.

I myself have used this pattern to implement a dynamic console in a game. At run-time, sections of code register commands into the console. The console then accepts textual input, and pattern matches against a Name() method of each command, and upon finding a match it calls Execute() on the command. I had implemented this before discovering Design Patterns, so could have saved myself a lot of work in knowing the intricacies of this pattern if I had read the book.

Strategy Design Pattern

January 9th, 2011 No comments

Strategy Design Pattern

Problem

How can we gain the ability to use different algorithms for like functionality, having the clients contain the code that implements the algorithms? How can we facilitate the extensibility of an algorithm set? How can we use different algorithms without complex conditionals?

Solution

The answer is the strategy. A strategy is a collation of algorithyms each implemented in its own concrete subclass. All the algorithms implement the same result, but may do so differently. Thus a separate class can access the functionality without having to contain it internally.

Consequences

Can implement a range of algorithms each encapsulated and easy to modify.

This provides a way to implement similar functionality without having to subclass the general class, only the algorithm.

One problem is that in order to determine which algorithm to use, the context class must know something about each algorithm.

Strategies increase the number of object in a system, but this can be alleviated by sharing the algorithm classes.

State Design Pattern

January 9th, 2011 No comments

Problem

When an object has different internal states, how can we implement the states without complicated boolean logic inside the class?

Solution

The answer is the state design pattern. In this pattern, the context object contains a state object, which represents the current state that the context object is in. It does this by implementing all the class methods of the context object. Whenever a context object receives a method call, it passes that call on to its state to execute the functionality. The context object changes the state object as needed to correctly relate to its internal state.

Consequences

Encapsulates specific functionality for specific states in its own class

Provides an easy way to extend the functionality of a context class. Just add more states.

State objects can be shared in certain cases to increase reuse.

Template Method Design Pattern

January 9th, 2011 No comments

Template Method Design Pattern

Problem

It is often tedious to implement many subclasses of a particular base class. It would be nice if there were a way to reference the existing structure, and only redefine some aspects of a class definition to make a new subclass.

Solution

A template is a very useful tool. It provides a way to replicate a base class in a sub class and only change what you want to without having to enter a lot of redundant code. When you use a template, you pass in parameters that configure your subclass to match you needs, without requiring you to completely define the new subclass. If you have ever used STL, then you are familiar with templates. STL has many predefined templates that can be used to make many useful subclasses. For example, in STL for C++ there is a template called list. You can make a list of floating point numbers with the line std::list<float>. This is quite a lot less trouble than creating your own implementation of a list class.

Consequences

To appropriately use a template, you must understand which methods can be overridden, and which methods must be overridden.

A template can provide a very efficient means of code reuse. If you can express your common functionality in a general way such that it can be templatized, then you have already increased code reuse.

Iterator Design Pattern

January 9th, 2011 No comments

Iterator Design Pattern

Problem

When working with lists it is often nice not to have to know the internal details of how the list is implemented. We may have different ways to traverse the list and do not want to clutter each list class with all the different ways to traverse it. How can we do this?

Solution

An iterator is a class that is separate from a list class that it works on. The iterator knows how the list is implemented and knows how to traverse it in a specific way. The list class has methods on it that will instantiate a object of the appropriate iterator class for use in traverse itself. If you are familiar with STL(Standard Template Library), then you are familiar with the concept.

Consequences

An iterator keeps track of its own state of traversal in a list, and as such multiple iterators can be active in different places without having to implement support for this in the list class. As well, iterators can implement any kind of traversal; forward, backward, etc. An iterator is a very powerful tool for use with lists, you can use an iterator specify a position in a list for use with higher level manipulation routines, such as sorting.

Mediator Design Pattern

January 9th, 2011 1 comment

Mediator Design Pattern

Problem

Partitioning a system can increase reusability. However, if as the number of classes increases then number of interconnections also increase that reduces the reusability. This is because the classes more and more rely on the existence of the others. How can we favor weak coupling and increase reusability?

Solution

A mediator provides and interface, and a level of indirection between dependant classes. A mediator, for instance, can sit between a list box, and a text entry field. When the list box changes, it tells the mediator, who then gets the text from the list box and passes it to the text entry box. So, the text entry box does not need to know about the list box, and does not have any interdependency with it. This is implemented by having both the text entry and list boxes derive off of a colleague base class which has a method Changed() which tells the mediator whenever the box changes. Then the mediator determines what needs to be done to maintain the system functioning properly.

Consequences

Changing how a system of objects interacts requires only subclassing the mediator, and the colleague classes remain unchanged. As well, the mediator provides the one place that controls the object, and determines how they communicate. A mediator also reduces the number of interface methods, as context specific methods are not required.