设计模式---策略模式

 


public class Context {
	private Strategy strategy;
	public Context(Strategy strategy) {
		this.strategy = strategy;
	}
	
	public void encrypt() {
		this.strategy.encrypt();
	}
}

public interface Strategy {

	//加密
	public void encrypt();
}

 


public class MDSStrategy implements Strategy{

	public void encrypt() {
		System.out.println("执行MDS加密");
	}

}
public class MD5Strategy implements Strategy{

	public void encrypt() {
		System.out.println("执行MD5加密");
	}
}

 


public class MainClass {
	public static void main(String[] args) {
//		Strategy stra = new MDSStrategy();
//		stra.encrypt();
		Context context = new Context(new MDSStrategy());
		context.encrypt();
	}
}

 

 策略模式具体实例

package com.ibeifeng.strategy;

public interface Strategy {

	public double cost(double num);
}
package com.ibeifeng.strategy;

public class StrategyA implements Strategy{

	public double cost(double num) {
		return num * 0.8;
	}

}

 

package com.ibeifeng.strategy;

public class StrategyB implements Strategy {

	public double cost(double num) {
		if(num >= 200) {
			return num - 50;
		}
		return num;
	}

}

 

package com.ibeifeng.strategy;

public class Context {
	private Strategy strategy;
	
	public Context(Strategy strategy) {
		this.strategy = strategy;
	}
	
	public double cost(double num){
		return this.strategy.cost(num);
	}
	
}

 

package com.ibeifeng.strategy;

public class MainClass {
	public static void main(String[] args) {
		double num = 200;
		Context context = new Context(new StrategyB());
		double newNum = context.cost(num);
		System.out.println("实际付账" + newNum + "元");
	}
}