使用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瓶

posted @ 2017-06-01 09:38  jzdwajue  阅读(256)  评论(0编辑  收藏  举报