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瓶