行为型模式~策略模式

定义:

也叫政策模式

定义一组算法,将每个算法都封装起来,并且使它们可以相互转换

 

角色:

  1. 环境角色:上下文角色,相当于调用者
  2. 抽象策略角色:对决策略,算法进行抽象,定义每个决策或算法必须有的方法和属性
  3. 具体策略:抽象的具体实现

优点:

  1. 策略模式提供了管理相关的算法族的办法。
  2. 提供了可以替换继承关系的办法
  3. 避免出现多重条件转换语句

缺点:

  1. 客户端必须知道所有的策略类,并决定使用哪一个
  2. 造成很多的策略类

场景:

  1. 多个类只是在算法或者行为上稍有不同的场景
  2. 算法需要自由切换的场景
  3. 需要屏蔽算法规则的场景

实例:商品打折结算

package 策略模式;

public abstract class DiscountStartegy {
	private double price;
	private int number;
	public double getprice(){
		return this.price;
	}
	public int getnumber(){
		return this.number;
	}
	public DiscountStartegy(double price,int number){
		this.price = price;
		this.number = number;
	}
	public abstract double calculate();
	
}
package 策略模式;

public class Wudiscount extends DiscountStartegy{

	public Wudiscount(double price, int number) {
		super(price, number);
		// TODO 自动生成的构造函数存根
	}

	@Override
	public double calculate() {
		// TODO 自动生成的方法存根
		return this.getprice()*getnumber();
	}
	
}
package 策略模式;

public class EightDiscount extends DiscountStartegy{

	public EightDiscount(double price, int number) {
		super(price, number);
		// TODO 自动生成的构造函数存根
	}

	@Override
	public double calculate() {
		// TODO 自动生成的方法存根
		return (this.getprice()*this.getnumber()*0.8D);
	}
	
}
package 策略模式;

public class NineDiscount extends DiscountStartegy{

	public NineDiscount(double price, int number) {
		super(price, number);
		// TODO 自动生成的构造函数存根
	}

	@Override
	public double calculate() {
		// TODO 自动生成的方法存根
		return (this.getprice()*this.getnumber()*0.9D);
	}
	
}
package 策略模式;

public class Main {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		DiscountStartegy shopping = new Wudiscount(60, 4);
		System.out.println("无折扣:"+shopping.calculate());
		System.out.println();
		shopping = new EightDiscount(62.3, 4);
		System.out.println("八折:"+shopping.calculate());
		System.out.println();
		shopping = new NineDiscount(60, 4);
		System.out.println("九折:"+shopping.calculate());
	}

}

无折扣:240.0

八折:199.36

九折:216.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值