DesignPatterns->策略模式

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

package com.zhiru;

/*
 * 策略模式
 * 组成要素:封装类,抽象策略,具体策略。
 * 
 */
//抽象策略,一般是一个接口
interface InterfaceStrategy {
	public abstract void detail();
}

// 具体的策略1
class S1 implements InterfaceStrategy {

	@Override
	public void detail() {
		// TODO Auto-generated method stub
		System.out.println("called S1 strategy" + S1.class);
	}

}

// /具体的策略2
class S2 implements InterfaceStrategy {
	public void detail() {
		System.out.println("called S2 strategy" + S2.class);
	}
}
//封装类.
class CallClass {
	private InterfaceStrategy is;

	public CallClass(InterfaceStrategy is) {
		this.is = is;
	}

	public void call() {
		is.detail();
	}
}

public class Strategy {
	public static void main(String[] args) {
		CallClass cc;
		cc=new CallClass(new S1());
		cc.call();
		cc=new CallClass(new S2());
		cc.call();
		
	}
}
参考博客:http://blog.csdn.net/zhengzhb/article/details/7609670
called S1 strategyclass com.zhiru.S1
called S2 strategyclass com.zhiru.S2

转载于:https://my.oschina.net/pangzhuzhu/blog/313007

你可能感兴趣的:(DesignPatterns->策略模式)