線程的兩種設計模式

1.模版模式: 父類實現算法,子類實現細節(一個線程啓動的start方法,爲什麼我們要去實現run方法呢,因爲Thread這個類的設計是採用template designer)


package com.jack.templatedesigner;

 abstract class StartProgram {
	protected String name;
	
	public StartProgram(String name){
		this.name = name;
	}

	//不想讓調用者關注到我們實現的細節,這也是面向對象思想封裝的一個體現
	abstract protected void run();
	
	//加個final 將不被繼承 因爲算法一旦確定就不允許更改, 更改也只允許算法的所有者也就是他的主人更改, 如
	//果調用者都可通過繼承進行修改,那麼算法將沒有嚴謹性可言
	public final void start(){
		run();
	}
}

package com.jack.templatedesigner;

class ThreadProgram  extends StartProgram{

	public ThreadProgram(String name) {
		super(name);
	}

	protected void run() {
		System.out.println("Thread name: "+this.name);
		
	}

 
}

public class ThreadTest{
	public static void main(String args[]){
		ThreadProgram thread = new ThreadProgram("thread 1");
		thread.start();
	}
}
 


2.策略模式:將具體業務邏輯與抽象分離 strtegy dsign

package com.jack.strategy;
/** 
 * 策略接口,主要是規範或者讓結構程序知道如何進行調用 
 */
public interface CalcStrategy {
	int calc(int x, int y);
}

package com.jack.strategy;

/** 
 * 程序的結構,裏面約束了整個程序的框架和執行的大概流程,但並未涉及到業務層面的東西 
 * 只是將一個數據如何流入如何流出做了規範,只是提供了一個默認的邏輯實現 
 * @author Administrator 
 */ 
class Caculator {
	private int x = 0;
	private int y = 0;
	private CalcStrategy strategy = null;
	
	public Caculator(int x,int y){
		this.x = x;
		this.y = y;
	}
	
	public Caculator(int x,int y,CalcStrategy strategy){
		this(x,y);
		this.strategy = strategy;
	}
	
	public int calc(int x, int y) {
		return x+y;
	}
	
	/** 
	 
	 * 只需關注接口,並且將接口用到的入參傳遞進去即可,並不關心到底具體是要如何進行業務封裝 
	 
	 * @return 
	 
	 */
	
	public int result(){
		if(null != strategy){
			return strategy.calc(x, y);      
		}
		
		return calc(x,y);
	}
	
	public void start(){
		System.out.println(result());
	}
	
}

class AddSrategy implements CalcStrategy{

	public int calc(int x, int y) {
		// TODO Auto-generated method stub
		return x + y;
	}
	
}

class SubStrategty implements CalcStrategy{

	public int calc(int x, int y) {
		// TODO Auto-generated method stub
		return x - y;
	}
	
}

package com.jack.strategy;

public class StrategyTest {
	public static void main(String args[] ) {
		//沒有任何策略時的結果
		Caculator c1 = new Caculator(1,1);
		c1.start();
		//傳入減法策略的結果
		Caculator c2 = new Caculator(10,30, new SubStrategty());
		c2.start();
		
		//看到這裏就可以看到策略模式強大了,算法可以隨意設置,系統的結構並不會發生任何變化
		Caculator c3  = new Caculator(2,3,new CalcStrategy(){
			public int calc(int x, int y) {
				// TODO Auto-generated method stub
				return x+10/(y+1)*2;
			}
		});
		
		c3.start();
	}
	
}

3.Thread  :template desigher   strategy designer 對照

package com.jack.thread1;

public class ThreadTest  {


	public static void main(String args[]){
		new Thread(new  Runnable(){

			public void run() {
				System.out.println(Thread.currentThread().getName());
			}}
		).start();
		
	}
}



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