設計模式說明

Produce by Shjy.Nicholas??????

E-Mail: shjy.nicholas@gmail.com

Version: 1.0??????????? ???????

?

說明 :

本文是 << 設計模式 -- 可復用面向對象軟件的基礎 >>, 英文名稱 "Design Patterns -- Elements of Reusable Object-Oriented Software"

一書的復習資料 . 原書的作者是 : Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides.

???????????????????? 譯者是 : 李英軍 , 馬曉星 , 蔡敏 , 劉建中 .

文中所表示的頁碼也是中文版的頁碼數 .

?

. OMT 表示法的簡單實例

類名

操作

數據

1.

?

?

?

?


??
public class Name {??????????? // Name
為類名

????? private String data ;????????? // data 為數據

????? public void operation() {}??????? // operation() 為操作

}

?

2. 實例化

對象

--->

?? Java , 就是 new 操作 , 此時會使對象內部的數據分配存儲空間 .

?

3. 繼承關系

?????

?? public class ParentClass {

????? public void sayHello() {

??????? System.out.println(“Hello in ParentClass”) ;

}

?? }

?

?? public class SubClass extends ParentClass {

????? public void sayHi() {

??????? System.out.println(“Hi in SubClass”) ;

????? }

?

????? public static void main(String [] args) {

??????? SubClass sc = new SubClass() ;

??????? sc.sayHello() ;

??????? sc.sayHi() ;

}

?? }

?

/**

?* 運行結果 :

?* Hello in ParentClass???? // 子類繼承了父類中的方法 SayHello()

* Hi in SubClass

?*/

?

?

4. 抽象類與具體類

abstract class AbstractClass {

?? public abstract void operation() ;

}

?

class ConcreteSubClass extends AbstractClass {

?? public void operation() {

????? System.out.println("operation...") ;

?? }

}

?

5. 混入類

java 中不直接支持多繼承 , 可以通過 implements 多個接口來實現 .

interface ExistingInterface {

?? void existingOperation() ;

}

?

interface Mixin {

?? void mixinOperation() ;

}

?

class AugmentedClass implements ExistingInterface, Mixin {

?? public void existingOperation() {

????? System.out.println("existingOperation()") ;

?? }

??

?? public void mixinOperation() {

????? System.out.println("mixinOperation()") ;

?? }

}

?

?

. 委托

class Rectangle {

?? public int width ;

?? public int height ;

??

?? public int area(){

????? return width * height ;

?? }

}

?

class Window {

?? Rectangle rectangle = new Rectangle() ;

??

?? public int area() {

????? return rectangle.area() ;

?? }

}

?

. Lexi 說明 .

1. 設計中涉及到 7 種設計模式 , 分別是 Abstract Factory, Composite, Strategy, Decorator, Bridge, Command, Iterator.

?

2. 設計問題 :

u????? 文檔結構 :Lexi 的用戶可以直接操縱行 , , 圖形 , 表等子結構 .

使用到的模式 : 組合模式 .

u????? 格式化 : 將一個圖元集合分解為若干行 .

格式化不同于表示 ,Lexi 必須將文本分解成行 , 將行分解成列等操作 , 同時還要滿足用戶的高層次要求 , : 指定邊界寬度 , 縮進大小和表格形式 , 是否隔行顯示以及其他可能的許多格式限制條件 .

使用的模式 : 策略模式 .

u????? 修飾用戶界面 :

支持兩種修飾 :

n??????? 在文本編輯區域周圍加邊界以界定文本頁 .

n??????? 加滾動條 .

???使用的模式 : 裝飾模式 .

u????? 支持多種視感標準 : 支持多種視感標準 , 以滿足平臺移植的要求 .

使用模式 : 抽象工廠 .

u????? 支持多種窗口系統 : 解決移植中的窗口環境 .

使用模式 : 橋接模式 .

u????? 用戶操作 : 通過文檔的 WYSIWYG( 所見即所得 ) 得到 , 并支持撤銷和重做功能 , 以及命令歷史記錄 .

使用得模式 : 命令模式 .

u????? 拼寫檢查和連字符 :

1. 訪問以圖元形式存在的 , 分散在文檔結構中的信息 .

2. 分析這些信息

使用的模式 : 迭代器模式 .

. 重要模式的說明 :


1. Abstract Factory
抽象工廠模式

???
???抽象工廠模式涉及到以下角色 :

u????? 抽象工廠角色 : 擔任這個角色的是工廠方法模式的核心 , 它是與應用系統的商業邏輯無關的 .

u????? 具體工廠角色 : 這個角色直接在客戶端的調用下創建產品的實例 .

u????? 抽象產品角色 : 擔任這個角色的類是工廠方法模式所創建的對象的父類 , 或它們共同擁有的接口 .

u????? 具體產品角色 : 抽象工廠模式所創建的任何產品對象都是某一個具體產品類的實例 .


在書
P58 頁的結構圖中 ,

抽象工廠角色 :AbstractFactory

具體工廠角色 :ConcreteFactory1, ConcreteFactory2

抽象產品角色 :AbstractProductA, AbstractProductB

具體產品角色 :ProductA1, ProductA2, ProductB1, ProductB2

?

2. Builder 生成器模式


Builder
涉及到的角色 : ( 括號內為所舉例子中所對應的類名 )

u????? 抽象創造者 (Builder)

u????? 具體創造者 (ConcreteBuilder)

u????? 導演者 (Director)

u????? 產品 (Product)


舉例說明
:

abstract public class Builder {

public abstract void buildPart1();

public abstract void buildPart2();

?

public abstract Product retrieveResult();

}

?

public class ConcreteBuilder extends Builder {

private Product product = new Product() ;

?

public void buildPart1() {

?? product.setPart1(“Part1 be build”) ;

}

?

public void buildPart2() {

?? product.setPart2(“Part2 be build”) ;

}

?

public Product retrieveResult(){

????? return product;

}

}

?

public class Director {

private Builder builder;

?

public Director(Builder builder) {

this.builder = builder;

}

?

public Product construct()

builder.buildPart1();

builder.buildPart2();

return builder.retrieveResult();

}

}

?

public class Product {

?? private String part1 = null ;

?? private String part2 = null ;

?

public Product() {}

?

?? public void setPart1(String part1){

????? this.part1 = part1 ;

?? }

?

?? public String getPart1() {

????? return this.part1 ;

?? }

?

?? public void setPart2(String part2){

????? this.part2 = part2 ;

?? }

?

?? public String getPart2() {

????? return this.part2 ;

?? }

??

?? public String toString(){

????? System.out.println(“part1: ” + this.getPart1()) ;

????? System.out.println(“part2: ” + this.getPart2()) ;

?? }

}

?

public class Client {

private Director director = null ;

?? private Builder builder = null ;

?

public void doBuild() {

????? director = new Director(new ConcreteBuilder());

????? System.out.println(director. construct()) ;

}

}

?

?

3. Composite 合成模式


涉及到的角色
:

u????? 抽象構件 (Component)

u????? 樹葉構件 (Leaf)

u????? 樹枝構件 (Conmposite)

?

舉例 :

public interface Component {

Composite getComposite();

?

void sampleOperation();

}

?

public class Leaf implements Component {

public Composite getComposite(){

return null;

}

?

public void sampleOperation(){

System.out.println("leaf say hello") ;

}

}

?

?

import java.util.Vector;

import java.util.Enumeration;

?

public class Composite implements Component{

?? private Vector componentVector = new java.util.Vector();

?

public Composite getComposite(){

return this;

}

?

public void add(Component component){

componentVector.addElement(component);

}

?

public void remove(Component component){

componentVector.removeElement(component);

}

?

public Enumeration components(){

return componentVector.elements();

}

?

?? public void sampleOperation(){

Enumeration enumeration = components();

while (enumeration.hasMoreElements()){

((Component)enumeration.nextElement())

.sampleOperation();

}

}

}

?

?

4 Strategy 策略模式


對應于
P209 的結構圖 ,


public class Context{

?? private Strategy strategy;

?

?? public Strategy setStrategy(Strategy strategy) {

????? this.strategy = strategy ;

?? }

??

public void contextInterface(){

this.strategy.strategyInterface();

}

}

?

?

abstract public class Strategy{

public abstract void algorithmInterface();

}

?

public class ConcreteStrategyA extends Strategy{

public void algorithmInterface(){

System.out.println("A") ;

}

}

?

public class ConcreteStrategyB extends Strategy{

public void algorithmInterface(){

System.out.println("B") ;

}

}

?

public class ConcreteStrategyC extends Strategy{

public void algorithmInterface(){

System.out.println("C") ;

}

}

?

?

5.Decorator 裝飾模式


基于
P116 的結構圖 , 有如下代碼 :


public interface Component{

?? void operation();

}

?

public class ConcreteComponent implements Component{

??? public void operation(){

????? // 給對象添加一些指責

?? }

}

?

public class Decorator implements Component{

?? private Component component = null ;

??

?? public Decorator(Component component){

????? this.component = component;

?? }

?

public void operation(){

????? component.operation();

?? }

}

?

public class ConcreteDecorator extends Decorator{

??? public void operation(){

????? super.operation();

// 調用 Component 對象的 operation 方法 , 來給組件添加指責

?? }

}

?

6.Bridge 橋接模式


基于
P101 的結構圖 :


abstract public class Abstraction{

?? private Implementor imp;

??

?? public void operation(){

????? imp.operationImp();

?? }

}

?

public class RefinedAbstraction extends Abstraction{

?? public void operation() {

????? super.operation() ;

????? // 可以增加進一步的處理

?? }

}

?

abstract public class Implementor{

?? public abstract void operationImp();

}

?

public class ConcreteImplementorA extends Implementor{

?? public void operationImp(){

????? System.out.println(

"Do something in ConcreteImplementorA ...");

?? }

}

?

public class ConcreteImplementorB extends Implementor{

?? public void operationImp() {

????? System.out.println(

"Do something in ConcreteImplementorB ...");

?? }

}

?

?

7.Command 命令模式


基于
P157, 有如下示例 :


public class Receiver {

?? public Receiver() {}

?

?? public void action() {

????? System.out.println("Action has been taken.");

?? }

}

?

public interface Command {

?? void execute();

}

?

public class ConcreteCommand implements Command{

?? private Receiver receiver;

??

public ConcreteCommand(Receiver receiver) {

????? this.receiver = receiver;

?? }

?

?? public void execute() {

????? receiver.action();

?? }

}

?

public class Invoker {

?? private Command command;

?

?? public Invoker(Command command){

????? this.command = command;

?? }

?

?? public void action() {

????? command.execute();

?? }

}

?

public class Client {

?? public static void main(String [] args) {

????? Receiver receiver = new Receiver();

????? // 關鍵 : 將接受者綁定到一個動作

????? Command command = new ConcreteCommand(receiver);

????? Invoker invoker = new Invoker( command );

?

????? invoker.action();

?? }

}

?

?

8. Iterator 迭代器模式


基于
P172, 有如下代碼 :


public interface Iterator{

?? void first();

?? void next();

?? boolean isDone();

?? Object currentItem();

}

?

public class ConcreteIterator implements Iterator{

?? private ConcreteAggregate agg;

?? private int index = 0;

?? private int size = 0;

?

?? public ConcreteIterator(ConcreteAggregate agg) {

????? this.agg = agg;

????? size = agg.size();

????? index = 0 ;

?? }

?

?? public void first() {

????? index = 0 ;

?? }

?

?? public void next(){

????? if (index < size){

??????? index++;

????? }

?? }

?

?? public boolean isDone() {

????? return (index >= size);

?? }

?

?? public Object currentItem() {

????? return agg.getElement(index);

?? }

}

?

abstract public class Aggregate{

?? public Iterator createIterator() {

????? return null;

?? }

}

?

public class ConcreteAggregate extends Aggregate{

?

?? private Object objs[]= {" Item1 ",

???????????????????????????" Item2 ",

?????????????????????????? " Item3 ",

?????????????????????????? "Item4 "
???????????????????????????"Item5"};

?

?? public Iterator createIterator(){

????? return new ConcreteIterator(this);

?? }

?

?? public Object getElement(int index) {

????? if (index < objs.length) {

??????? return objs[index];

?? ?? } else {

??????? return null;

????? }

?? }

?

?? public int size(){

????? return objs.length;

?? }

}

?

public class Client{

?? private Iterator it;

?? private Aggregate agg = new ConcreteAggregate();

?

?? public void operation(){

????? it = agg.createIterator();

?

????? while( !it.isDone() ){

??????? System.out.println(it.currentItem().toString());

??????? it.next();

????? }

?? }

?

?? public static void main(String[] args) {

????? Client client = new Client();

????? client.operation();

?? }

}

?

?