设计模式_策略模式(Strategy)

package com.strategy;

/**
 * 策略接口
 * @author 83998
 *
 */
public interface Strategy {
	double compute();
}

package com.strategy;

/**
 * 加法策略类
 * @author 83998
 *
 */
public class AddStrategy implements Strategy {

	private Integer a;
	private Integer b;

	public AddStrategy(Integer a, Integer b) {
		super();
		this.a = a;
		this.b = b;
	}

	@Override
	public double compute() {
		return a + b;
	}

	public Integer getA() {
		return a;
	}

	public void setA(Integer a) {
		this.a = a;
	}

	public Integer getB() {
		return b;
	}

	public void setB(Integer b) {
		this.b = b;
	}

}

package com.strategy;

/**
 * 减法策略类
 * @author 83998
 *
 */
public class SubStrategy implements Strategy {

	private Integer a;
	private Integer b;

	public SubStrategy(Integer a, Integer b) {
		super();
		this.a = a;
		this.b = b;
	}

	@Override
	public double compute() {
		return a - b;
	}

	public Integer getA() {
		return a;
	}

	public void setA(Integer a) {
		this.a = a;
	}

	public Integer getB() {
		return b;
	}

	public void setB(Integer b) {
		this.b = b;
	}
}

package com.strategy;

/**
 * 策略执行者
 * @author 83998
 *
 */
public class Manager {
	private Strategy stragety;

	public Manager(Strategy stragety) {
		super();
		this.stragety = stragety;
	}

	public double start() {
		return stragety.compute();
	}

	public Strategy getStragety() {
		return stragety;
	}

	public void setStragety(Strategy stragety) {
		this.stragety = stragety;
	}

}

package com.strategy;

/**
 * 测试类
 * @author 83998
 *
 */
public class Test {
	public static void main(String[] args) {
		Manager m = new Manager(new AddStrategy(2, 3));
		System.out.println(m.start());

		double pi = new Manager(new Strategy() {

			@Override
			public double compute() {
				return Math.PI;
			}
		}).start();

		System.out.println(pi);
	}
}

发布了340 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Chill_Lyn/article/details/103647631