# 设计模式沉思录

919人阅读 评论(1)

## 1.抽象（Abstraction）

《Code Complete》说过，软件开发的首要任务就是处理复杂度，而降低复杂度的武器就是抽象。所以说抽象隐藏了背后的细节，让你拿来即用，一层一层地构造更加复杂的抽象概念。从这一点上来说，抽象就像软件模块一样，从硬件到操作系统到编译器到编程语言，从ISO模型的物理层到链路层到网络层到应用层等，每一层抽象都各司其职，对外隐藏细节，内部处理复杂。那么设计模式是不是一种抽象呢？答案就在下文。

## 2.模式：失败的抽象

A design pattern is a commonality found in different pieces of code. An abstraction is also a commonality between pieces of code, but it’s typically a commonality that has been factored out, for example, into a library function that can be reused. A design pattern is a failed abstraction. It’s a commonality that for some reason couldn’t be factored out. Instead it gets described in English (or other natural language) and if you want to use it you read the English and use that as a guide to writing code. It’s a lot easier to use an abstraction because then you can just call it from your code instead of rewriting it. What can be abstracted depends to some extent on your programming language. For example in Java you might use the visitor pattern. But in ocaml or Haskell you just write a recursive function. The ability to visit each element of a tree structure is already built right into functional languages obviating the need for a pattern.

Mathematics notation is very flexible. If it doesn’t already do what you want you can invent new structures and notation. This means that if you see common structure in two separate proofs then you have a good chance of extracting out the common structure and making that a reusable theorem. For example there are counting arguments that work for both the set of integers and the set of Rubik cube moves. Both these sets form groups and the common structure can be abstracted out into a theorem of group theory.

But sometimes the structure shared between two theorems is too difficult to factor out. Maybe it’s a bit vague, or the similarity isn’t an exact correspondence. Then you have a design pattern. I think these things correspond to what mathematicians might call an “argument” or a “trick”. For example there’s the Proof by infinite descent. I don’t think there’s a single theorem that encompasses all descent arguments. So it’s a pattern rather than a single abstraction. Or maybe Terry Tao’s amplification trick. Again, I don’t think there’s one theorem at work here. It’s more of an approach to solving a class of problem so again it’s a pattern. Another example from Tao might be finitization (Page on York).

## 3.你的模式，我的语言特性

import time

def timeit(func):
def inner(num):
start = time.time()
ret = func(num)
print 'Cost time: {} (s)'.format(time.time()-start)
return ret
return inner

@timeit
def do_sth_slow(num):
time.sleep(1)
return num * num

print 'Result: {}'.format(do_sth_slow(5))
"""
Cost time: 1.00513315201 (s)
Result: 25
"""

1
0

个人资料
• 访问：3389636次
• 积分：24486
• 等级：
• 排名：第318名
• 原创：314篇
• 转载：56篇
• 译文：3篇
• 评论：1592条
博客专栏
 探索编程的本质 文章：3篇 阅读：7869
 内存计算 文章：18篇 阅读：163025
最新评论