Solution Architect: "But you can use patterns."
Dumb Developer: "Yes, but can I get it as an ActiveX control?"
This article is expected to:
- Introduce patterns to you in a simple, human readable (?) way
- Train you how to really 'Apply' patterns (you can learn patterns easily, but to apply them to solve a problem, you need real design skills)
- Provide you with a fair idea regarding the contexts for applying the following patterns: Builder, Observer, Strategy, and Decorator (well, they are few popular design patterns)
- Demonstrate you how to apply the Observer pattern to solve a design problem
In this entire article, you will go through the following steps:
- You will model a very simple football game engine.
- You will identify the design problems in your football game engine.
- You will decide which patterns to use to solve your design problems.
- You will actually use the observer pattern to solve one of your design problems.
As a prerequisite, you may need to get a grip on reading and understanding UML diagrams.
Using The Code
The related zip file includes the code, UML designs (in Visio format), and so forth. After reading this article, you may download and extract the zip file—using a program like Winzip—to play with the source code.
An Overview Of Design Patterns
Even without much knowledge about design patterns, designers and developers tend to reuse class relationships and object collaborations to simplify the design process. In short, "A Design pattern consists of various co-operating objects (classes, relationships, and so on)". They provide solutions for common design problems. More than anything else, they offer a consistent idiom for designers and programmers to speak about their design. For example, you can tell a friend that you used a 'Builder' pattern to address some design specifications in your project.
A consistent classification of patterns for common design problems are provided by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides [also known as the Gang of Four (GOF)]. The Gang of Four (GOF) patterns are generally considered the foundation for all other patterns.
The basic principle of using patterns is reusability. Once a problem is addressed some way, you are not really expected to re-invent the wheel if you properly understand the concept of pattern-centric software engineering. Here are some important points to remember about design patterns.
- A Design Pattern is not code. It is, in fact, an approach or a model that can be used to solve a problem.
- Design Patterns are about design and interaction of objects; they provide reusable solutions to solve common design problems.
- A Design Pattern is normally represented with the help of a UML diagram.
Some real hands-on experience with patterns may provide you a better idea!!
Architecting Your (Simple) Football Engine
You are working with a popular computer game developing company, and they made you the Solution Architect of one of their major projects—a Soccer (Football) Game Engine (nice, huh?). Now, you are leading the process of designing the entire Football game engine, and suddenly you have a lot of design considerations, straight away. Take a look:
- How do you identify the entities in your game system?
- How do you identify the design problems?
- How do you apply patterns to address your design specifications?
First of all, you need to identify the objects you use in your game engine. For this, you should visualize how the end user is going to use the system. Assume that the end user is going to operate the game in the following sequence (to keep things simple).
- Start the game
- Select two teams
- Add or remove players to/from a team
- Pick a playground
- Begin playing the game
Your system may have a number of PlayGrounds in it, a number of Teams, and so forth. To list a few real-world objects in the system, you have the following:
- A Player who plays soccer
- A Team with various players in it
- A Ball that is handled by various players
- A PlayGround where the match takes place
- A Referee on the ground to control the game
Also, you may need some logical objects in your game engine; for example,
- A Game that defines a football game, constitutes teams, ball, referee, playground, and the like.
- A GameEngine to simulate a number of games at a time.
- A TeamStrategy to decide a team's strategy when playing.
So, here is a very abstract view of the system. The boxes represent classes in your system, and the connectors depict 'has' relationships and their multiplicity. The arrow head represents the direction of reading. In other words, a GameEngine has (can simulate) Games. A Game has (consists of) three referees, one ball, two teams, and one ground. A team can have multiple players, and one strategy at a time.
Figure 1: High level view
Identifying Design Problems
Now, you should decide:
- How these objects are structured
- How they are created
- How they behave when they interact each other, to formulate the design specifications
First of all, you have to write down a minimum description of your soccer engine to identify the design problems. For example, here are few design problems related to some of the objects that were identified earlier.
- Ball: When the position of a ball changes, all the players and the referee should be notified straight away.
- Team and TeamStrategy: When the game is in progress, the end user can change the strategy of his team (for example, from Attack to Defend).
- Player: A player on a team should have additional responsibilities, such as Forward, Defender, and so forth, that can be assigned during runtime.
- PlayGround: Each ground constitutes of gallery, ground surface, audience, and the like; each ground has a different appearance.
So now, see how to identify the patterns to address these design problems.
Identifying Patterns to Use
Have a look at the design problems you identified above (yes, do it once more). Now, see how to address these problems by using design patterns.
1: Addressing the design problems related to the 'Ball'
First of all, take the specifications related to the ball. You need to design a framework such that when the state (position) of the ball is changed, all the players and the referee are notified regarding the new state (position) of the ball. Now, generalize the problem:
Specific Design Problem: "When the position of a ball changes, all the players and the referee should be notified straight away."
Problem Generalized: "When a subject (in this case, the ball) changes, all its dependents (in this case, the players) are notified and updated automatically."
Once you have such a design problem, you refer to the GOF patterns, and suddenly you may find out that you can apply the 'Observer' pattern to solve the problem.
Observer Pattern: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
In this case, you used this pattern because you need to notify all the players when the position of the ball is changed.
2: Addressing the design problems related to 'Team' And 'TeamStrategy'
Next, you have to address the specifications related to the team and team strategy. As was discussed earlier, when the game is in progress, the end user can change the strategy of his team (for example, from Attack to Defend). This clearly means that you need to separate the Team's Strategy from the Team that uses it.
Specific Design Problem: "When the game is in progress, the end user can change the strategy of his team (as in from Attack to Defend)"
Problem Generalized: "You need to let the algorithm (TeamStrategy) vary independently from clients (in this case, the Team) that use it."
Then, you can chose the 'Strategy' pattern to address the above design problem.
Strategy Pattern: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
3: Addressing the design problems related to 'Player'
Now, address the design specifications related to the player. From your problem definition, it is clear that you need to assign responsibilities (such as forward or defender) to each player during runtime. At this point, you can think about sub classing (inheritance) by creating a player class, and then inheriting classes such as Forward or Defender from the base class. But, the disadvantage is that when you do sub classing, you cannot separate the responsibility of an object from its implementation.
In your case, sub classing is not the suitable method because you need to separate the responsibilities such as 'Forward', 'Midfielder', 'Defender' and so forth from the Player implementation. A player can be a 'Forward' one time; some other time, the same player can be a 'Midfielder'.
Specific Design Problem: "A player on a team should have additional responsibilities, such as Forward or Defender, that can be assigned during runtime."
Problem Generalized: "You need to attach additional responsibilities (such as Forward or Midfielder) to the object (in this case, the Player) dynamically, without using sub classing."
Then, you can chose the 'Decorator' pattern to address the above design problem.
Decorator Pattern: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing to extend functionality.
4: Addressing the design problems related to 'PlayGround'
If you take a look at the specifications of Ground, you see that a ground's appearance is decided by various sub units such as gallery, surface of the ground, audience, and so on. The appearance of the ground may vary according to these sub units. Hence, you need to construct the ground in such a way that the construction of the ground can create different representations of the ground. In other words, a ground in Italy may have different gallery structure and surface when compared to a ground in England. But, the game engine may create both these grounds by calling the same set of functions.
Specific Design Problem: "Each ground constitutes of gallery, ground surface, audience, and so forth; each ground has a different appearance."
Problem Generalized: "You need to separate the construction of an object (ground) from its representation (the appearance of the ground) and you need to use the same construction process to create different representations."
Builder Pattern: Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Now, you can chose the 'Builder' pattern to address the above design problem.