啥叫模式? 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與實現是分離的.
你的類終歸是給自己或別人使用的,在調用者的眼里, 非常簡單, 管你里面是怎么實現的呢,
反正我知道你能給我一個迭代器就夠了, 這里面就體現了面向接口編程的好處. 也就是按契約編程