何时使用哪种设计模式?

我非常喜欢设计模式,但我发现很难看到什么时候可以应用一个。我已经阅读了很多解释设计模式的网站。我确实能够理解其中的大部分,但是我发现在我自己的情况下很难识别出一种模式。

这就是我问这个问题的原因。当使用哪种设计模式时,是否有任何指导方针/警钟。

例如,如果您正在执行 switch 语句以确定需要创建哪个对象,那么您可能希望使用工厂设计模式。因此,本例中的 switch 语句是使用 Factory 模式的“警钟”。

那么,你知道更多的“警钟”来确定设计模式吗?

126191 次浏览

Usually the process is the other way around. Do not go looking for situations where to use design patterns, look for code that can be optimized. When you have code that you think is not structured correctly. try to find a design pattern that will solve the problem.

Design patterns are meant to help you solve structural problems, do not go design your application just to be able to use design patterns.

Learn them and slowly you'll be able to reconize and figure out when to use them. Start with something simple as the singleton pattern :)

if you want to create one instance of an object and just ONE. You use the singleton pattern. Let's say you're making a program with an options object. You don't want several of those, that would be silly. Singleton makes sure that there will never be more than one. Singleton pattern is simple, used a lot, and really effective.

I completely agree with @Peter Rasmussen.

Design patterns provide general solution to commonly occurring design problem.

I would like you to follow below approach.

  1. Understand intent of each pattern
  2. Understand checklist or use case of each pattern
  3. Think of solution to your problem and check if your solution falls into checklist of particular pattern
  4. If not, simply ignore the design-patterns and write your own solution.

Useful links:

sourcemaking : Explains intent, structure and checklist beautifully in multiple languages including C++ and Java

wikipedia : Explains structure, UML diagram and working examples in multiple languages including C# and Java .

Check list and Rules of thumb in each sourcemakding design-pattern provides alram bell you are looking for.