首页 > 代码库 > 线程的两种设计模式

线程的两种设计模式

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();
		
	}
}