使用drools解决小明喝汽水的问题

问题描述:

1、小明手上有50元钱;

2、1元钱可以买一瓶饮料;

3、2个空瓶可以兑换一瓶饮料;

4、问题是:最终小明可以喝多少瓶饮料 ? 


首先,新建maven项目,加入drools依赖

<dependency>
	<groupId>org.drools</groupId>
	<artifactId>drools-core</artifactId>
	<version>6.2.0.Final</version>
</dependency>
<dependency>
	<groupId>org.drools</groupId>
	<artifactId>drools-compiler</artifactId>
	<version>6.2.0.Final</version>
</dependency>


package com.lala.bean;

public class Drinks 
{
	private Integer money;
	private Integer total = 0;	//喝的饮料数量
	private Integer bottle = 0; //空瓶子数量
	
	public Drinks(Integer money)
	{
		this.money = money;
	}
	public Integer getMoney() {
		return money;
	}
	public void setMoney(Integer money) {
		this.money = money;
	}
	public Integer getTotal() {
		return total;
	}
	public void setTotal(Integer total) {
		this.total = total;
	}
	public Integer getBottle() {
		return bottle;
	}
	public void setBottle(Integer bottle) {
		this.bottle = bottle;
	}
}


drools规则:

package com.drink;
import com.lala.bean.Drinks;

rule "money"
	salience 2
    when
    	$d:Drinks(money > 0);
    then
    	modify($d){
	    	setMoney($d.getMoney() - 1),//买一瓶
	    	setTotal($d.getTotal() + 1),//喝一瓶
	    	setBottle($d.getBottle() + 1);//增加一个空瓶(每喝一瓶,就增加一个空瓶)
    	};
end

rule "bottle"
	salience 1
    when
    	$d:Drinks(bottle >= 2);
    then
    	modify($d){
    		setBottle($d.getBottle() - 2),//用2个空瓶换一瓶
	    	setTotal($d.getTotal() + 1),//喝一瓶
	    	setBottle($d.getBottle() + 1);//增加一个空瓶(每喝一瓶,就增加一个空瓶)
    	};
end


测试:

package com.lala.mydrools;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import com.lala.bean.Drinks;

public class Test 
{
	static KieSession getSession()
    {
        KieServices ks = KieServices.Factory.get();
         
        KieContainer kc = ks.getKieClasspathContainer();
 
        return kc.newKieSession("simpleRuleKSession");
    }
    public static void main(String[] args)
    {
        KieSession ks = getSession();
        
        Drinks dr = new Drinks(50);
        ks.insert(dr);
        int count = ks.fireAllRules();
        System.out.println("总执行了"+count+"条规则");
        System.out.println("总共可以喝:" + dr.getTotal() + "瓶");
        ks.dispose();
    }
}


最后,输出结果为:

总执行了99条规则
总共可以喝:99瓶

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值