How to Make a Pattern in C++ Code
Like knitting patterns, programming patterns are tools for duplicating good design. Douglas Schmidt of Vanderbilt University describes C++ patterns as a way to capture successful solutions to particular programming problems so that programmers can reuse the solutions later. Structural patterns describe how to organize and connect objects. Behavioral patterns capture ways to organize code. Creational patterns record methods to organize code to create software objects. These groups have further subdivisions: Factor patterns, for example, create generalized software objects -- program components -- rather than objects tailored to specific problems.
Instructions
-
-
1
Define the purpose of the pattern and the problem you want to solve. Vanderbilt's Schmidt recommends online that you define the problem in general terms: Successful patterns have an existence independent of how users implement them in specific situations. Patterns are a good solution for recurring problems rather than unique incidents.
-
2
List the demands, or forces, that will act on your pattern. If you code software for a stock-quote service, for example, the forces include the multiple investors checking the market, each of whom has a different perspective and interest. A successful pattern provides usable information regardless of how individual observers and their needs change.
-
-
3
Draw up the pattern's structure, an abstract, graphic representation of what you want it to do. Identify software objects for the pattern to employ in accomplishing its goal; what each object's role is; and how the objects collaborate together.
-
4
Identify the positive and negative consequences of adopting your proposed pattern. If your pattern allows you to apply a successful solution quickly to an entire class of recurring problems, that's a plus, for example. The negative might be that it's less efficient than solutions tailored to each individual problem.
-
5
Write the code to create your pattern. Test it once you finish to make sure everything works the way you want.
-
1
Tips & Warnings
Avoid antipatterns, which resemble regular C++ patterns but don't provide good solutions. Copying and pasting existing code without rewriting it for more generic use is an antipattern. So is embedding assumptions about the programming environment into the software; establishing an overly complicated interface; and reusing a pattern after someone has developed a newer, better solution.