常用設計模式(下)

結合原理與實例介紹以下設計模式:適配器,裝飾,組合,模板方法,策略,責任鏈,觀察者,迭代器等設計模式。

1.適配器模式

定義:將一個類的接口轉換成客戶希望的另外一個接口,使得原本由於接口不兼容而不能一起工作的那些類能一起工作。
實際運用:SpringMVC的handlerAdapter
實例:電源轉接頭

public interface PowerTarget {
	public int output5V();
}
public class PowerAdaptee {
	private int output = 220;
	public int output220V() {
		System.out.println("電源輸出電壓:" + output);
		return output;
	}
}

public class PowerAdapter extends PowerAdaptee implements PowerTarget{
	//也能夠以組合的方式傳入適配對象
	@Override
	public int output5V() {
		int output = output220V();
		System.out.println("電源適配器開始工作,此時輸出電壓是:" + output);
        output = output/44;
        System.out.println("電源適配器工作完成,此時輸出電壓是:" + output);
        return output;
	}
}
public class Test {
	public static void main(String[] args) {
		PowerTarget target = new PowerAdapter();
		target.output5V();
	}
}

2.裝飾者模式

定義:指在不改變現有對象結構的情況下,動態地給該對象增加一些職責(即增加其額外功能)的模式。
實際運用:java io類(new BufferedReader(new FileReader(new File("")));

3.組合模式

定義:它是一種將對象組合成樹狀的層次結構的模式,用來表示“部分-整體”的關係,使用戶對單個對象和組合對象具有一致的訪問性。
只有爲(a is b)關係是才能用繼承;
當爲(a has b)時就應用組合。
組合相對於繼承更加靈活,<< effective java >>這本書上面也有說組合優先於繼承

4.模板方法模式

定義:定義一個操作中的算法骨架,而將算法的一些步驟延遲到子類中,使得子類可以不改變該算法結構的情況下重定義該算法的某些特定步驟。
實際運用:看看Spring IOC容器的初始化流程,在AbstractApplicationContext類的refresh方法中:

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}
				destroyBeans();

				cancelRefresh(ex);
				throw ex;
			}
			finally {
				resetCommonCaches();
			}
		}
	}

5.策略模式

定義:模式定義了一系列算法,並將每個算法封裝起來,使它們可以相互替換,且算法的變化不會影響使用算法的客戶
實例:比如validator接口,我們可以爲不同的對象定義不同的驗證策略。

6.責任鏈模式

定義:爲了避免請求發送者與多個請求處理者耦合在一起,將所有請求的處理者通過前一對象記住其下一個對象的引用而連成一條鏈;當有請求發生時,可將請求沿着這條鏈傳遞,直到有對象處理它爲止。
我曾看到:有把整個下訂單流程封裝爲一個鏈,還有mybatis底層攔截器鏈,這些相似設計。
示例:

abstract class Handler {

	private Handler next;
	public abstract void handle(String request);
	public Handler getNext() {
		return next;
	}
	public void setNext(Handler next) {
		this.next = next;
	}
}

public class FirstHandler extends Handler{

	@Override
	public void handle(String request) {
		if(request.equals("one")) {
			System.out.println("firstHandler ...");
		}else {
			if(getNext() != null) {
				getNext().handle(request);
			}else {
				System.out.println("No one handle...");
			}
		}
		
	}

}

public class SecondHandler extends Handler{
	@Override
	public void handle(String request) {
		if(request.equals("two")) {
			System.out.println("SecondHandler ...");
		}else {
			if(getNext() != null) {
				getNext().handle(request);
			}else {
				System.out.println("No one handle...");
			}
		}
		
	}
}

public class Test {
	public static void main(String[] args) {
		Handler handler1 = new FirstHandler();
		Handler handler2 = new SecondHandler();
		handler1.setNext(handler2);
		handler1.handle("two");
	}
}

7.觀察者模式

定義:指多個對象間存在一對多的依賴關係,當一個對象的狀態發生改變時,所有依賴於它的對象都得到通知並被自動更新。這種模式有時又稱作發佈-訂閱模式、模型-視圖模式
實際運用:spring中的各種listener,zookeeper的watch機制等。
示例:

public interface Observer {
	void notice();
}

abstract class Subject {
	// 存放所有的訂閱者
	protected List<Observer> observers = new ArrayList<Observer>();
	public void add(Observer observer) {
		observers.add(observer);
	}
	
	public void remove(Observer observer) {
		observers.remove(observer);
	}
	public abstract void notifyObserver();}

public class FireSubject extends Subject{

	@Override
	public void notifyObserver() {
		System.out.println("下達開火命令....");
		
		observers.forEach(ob -> {
			ob.notice();
		});
	}
}

public class TeamOneObserver implements Observer{

	@Override
	public void notice() {
		System.out.println("Team one 收到開火命令,fire.");
	}
}

public class TeamTwoObserver implements Observer{

	@Override
	public void notice() {
		System.out.println("Team two 收到開火命令,fire.");
	}
}

public class Test {
	public static void main(String[] args) {
		Subject subject = new FireSubject();
		Observer oneObserver = new TeamOneObserver();
		Observer twoObserver = new TeamTwoObserver();
		subject.add(oneObserver);
		subject.add(twoObserver);
		
		subject.notifyObserver();
	}
}

8.迭代器模式

定義:提供一個對象來順序訪問聚合對象中的一系列數據,而不暴露聚合對象的內部表示。
實際運用:這個模式我們應該很熟悉,Java中的集合類都提供了iterator方法遍歷,這就是迭代器模式的運用。

總結:遵循面向對象設計原則,根據具體的業務場景使用合適的設計模式。

參考:http://c.biancheng.net/view/1395.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章