1. 程式人生 > >初學Java 面向接口編程 命令模式 十八

初學Java 面向接口編程 命令模式 十八

易懂 人工 cto 接口編程 行為 con ria 一次 ref

分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!http://www.captainbed.net

命令模式 :把一個請求或者操作封裝到一個對象中。命令模式把發出命令的責任和執行命令的責任分割開,委派給不同的對象。命令模式允許請求的一方和發送的一方獨立開來,使得請求的一方不必知道接收請求的一方的接口,更不必知道請求是怎麽被接收,以及操作是否執行,何時被執行以及是怎麽被執行的。系統支持命令的撤消。

命令模式就像是把“處理行為”作為參數傳入一個方法,這個“處理行為”用編程來實現就是一段代碼

public interface Command
{
	//接口裏定義的process方法用於封裝"處理行為"
	void process(int[] target);
}

public class ProcessArray  
{
	public void process(int[] target,Command cmd)
	{
		cmd.process(target);
	}
}

public class PrintCommand implements Command 
{
	public void process(int[] target)
	
{ for(int tmp : target) { System.out.println("叠代輸出目標數組的元素:" + tmp); } } }

public class AddCommand implements Command 
{
	public void process(int[] target)
	{
		int sum = 0;
		for(int tmp : target)
		{
			sum += tmp;
		}
		System.out.println("數組元素的總和是:" + sum);
	}
}

public
class TestCommand { public static void main(String[] args) { ProcessArray pa = new ProcessArray(); int[] target = {3,-4,6,4}; //第一次處理數組,具體處理行為取決於PrintCommand pa.process(target,new PrintCommand()); //第二次處理數組,具體處理行為取決於AddCommand pa.process(target,new AddCommand()); } }
技術分享圖片
TestCommand為請求命令的一方,它只關心process方法,至於執行process方法的時候,具體做的什麽操作,由傳入的參數決定

process方法已經和它的處理行為分離開了,這就是請求命令一方與具體命令的解藕

上面還有一點不足的是客戶端需要知道PrintCommand和AddCommand這兩個類,這裏可以使用工廠模式來代替new,這樣客戶端不再需要知道眾多的Command對象,而是知道一個CommondFactory就足夠了

再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!http://www.captainbed.net

初學Java 面向接口編程 命令模式 十八