How do you know when to use design patterns?
Anyone can read the GoF book to learn what design patterns are and how to use them, but what is the process for figuring out when a design pattern solves a problem? Does the knowledge of the pattern drive the design, or is there a way to figure out how a pattern can be used to change a design?
In other words, are there patterns for Patterns?
Design patterns are supposed to provide a structure in which problems can be solved. When solving a real problem, you have to consider many tiny variations of a solution to that problem to see whether any fits a design pattern. In particular, you will probably need to generalise your problem, or its solution, in order to make a design pattern fit.
The answer is, it's an art. Knowing the design patterns is certainly an important step. One way to get used to this sort of thing is to study applications of design patterns, not just the patterns. Seeing many different applications of one pattern can help you over time to get better at mapping a task onto a pattern.
I would highly recommend reading Head First Design Patterns from O'Reilly. This explains how these patterns can be used in the real world.
I'd also add that don't try design too much with patterns in mind. More, look for "code smells" which a pattern might help solve.
Turn the question over: the pattern mtch you should be making is "what pattern fits my problem". Consider a really simple pattern, finding an element in an array. in C, it's something like
TYPE_t ary[SIZE] = // ... gets initialized somehow
size_t ix ; // Your index variable
for(ix=0; ix < SIZE; ix++){
if (ary[ix] == item) {
return ix ;
}
}
You don't look at the code and think "where can I use that", you look at the problem and say "do I know how to find an element in an array?"
With more extensive patterns is really works the same way. You need to have many many copies of a data structure that doesn't change often --- that makes you think "Flyweight." You want something that lives on both sides of a network boundary, you think Proxy.
When you study patterns, especially the GoF, ask yourself "what situations call for this pattern? Have I seen this pattern before? What could I have used this for in previous work? Where can I find an example of this in my own life?"
链接地址: http://www.djcxy.com/p/50222.html上一篇: 学习/实现设计模式(适用于新手)
下一篇: 你如何知道何时使用设计模式?