啥叫模式? Patterns in solutions come from patterns in problems.
针对某一类经常出现的问题所采取的行之有效的解决方案
"A pattern is a solution to a problem in a context."
"Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice."(Christopher Alexander -- A Pattern Language)
模式的四个基本要素:
1. 模式名称pattern name
2. 问题problem
3. 解决方案solution
4. 效果consequences
如何描述设计模式(十大特点)
1. 意图:描述,别名
2. 动机:场景
3. 适用性: 什么情况下
4. 结构: 类图, 序列图
5. 参考者
6. 协作
7. 效果
8. 实现
9. 应用
10. 相关模式
在实践中学习是最佳的方式, 所以先要掌握每个模式的十大特点,更加重要的是在实际应用中学习, 在水中学会游泳
以迭代器模式为例, Java中有一个Iterator接口
1 public interface Iterator
2 {
3 /**
4 * Tests whether there are elements remaining in the collection. In other
5 * words, calling <code>next()</code> will not throw an exception.
6 *
7 * @return true if there is at least one more element in the collection
8 */
9 boolean hasNext();
10
11 /**
12 * Obtain the next element in the collection.
13 *
14 * @return the next element in the collection
15 * @throws NoSuchElementException if there are no more elements
16 */
17 Object next();
18
19 /**
20 * Remove from the underlying collection the last element returned by next
21 * (optional operation). This method can be called only once after each
22 * call to <code>next()</code>. It does not affect what will be returned
23 * by subsequent calls to next.
24 *
25 * @throws IllegalStateException if next has not yet been called or remove
26 * has already been called since the last call to next.
27 * @throws UnsupportedOperationException if this Iterator does not support
28 * the remove operation.
29 */
30 void remove();
31 }
32
假如你的类中有一些聚集关系, 那么考虑增加一个iterator方法,以实现下面这个接口
public interface Iterable
{
/**
* Returns an iterator for the collection.
*
* @return an iterator.
*/
Iterator iterator ();
}
返回你自己实现的ConcreteIterator类, 这个ConcreteIterator当然是实现了
Iterator接口的
你会发现在遍历和迭代类中的这个成员的聚集元素时会有不同的感觉, 因为这个Iterator与实现是分离的.
你的类终归是给自己或别人使用的,在调用者的眼里, 非常简单, 管你里面是怎么实现的呢,
反正我知道你能给我一个迭代器就够了, 这里面就体现了面向接口编程的好处. 也就是按契约编程