Drools学习笔记2—Conditions / LHS 匹配模式&条件元素

  • Rule的LHS由条件元素(Conditional Elements—CE)和匹配模式(Patterns)组成
  • Patterns被用来指示出fact的字段约束
  • 每个约束必须为true才能让RHS的actions fire

 

测试代码,测试用获取KnowledgeBase方法:

  /**
   * 获取KnowledgeBase
   * @return
   * @throws Exception
   */
  private static KnowledgeBase readKnowledgeBase(String ruleName) throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource(ruleName, RuleTest.class), ResourceType.DRL);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (errors.size() > 0) {
        for (KnowledgeBuilderError error: errors) {
            System.err.println(error);
        }
        throw new IllegalArgumentException("Could not parse knowledge.");
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    return kbase;
}

 

使用到的fact对象

package com.bean;

import java.util.ArrayList;
import java.util.List;

public class Customer {
  private String name;
  private String Company;
  private Integer age;
  private String gender;
  private String city;
  private List accounts = new ArrayList();
  //省略set、get、toString方法  
}
package com.bean;

public class Account {
  private String name;
  private String status;
  private int num;
}

 

匹配模式(Patterns)

  • 没有字段约束的Pattern

    Person()

/**规则文件.drl**/
package com.sample
 
import  com.bean.Customer;
 
 
 rule "No args"
    when
       Customer()
    then
        System.out.println( "no massage" );
end


/**java测试代码,采用Junit测试**/
  /**
   * 没有字段约束的Pattern
   * @throws Exception
   */
  @Test
  public void testNoParam() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("NoParam.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    ksession.insert(customer);
    ksession.fireAllRules();
    logger.close();
  }

 

  • 有文本字段约束的Pattern

    Person( name == “bob” )

/**规则文件.drl**/
package com.sample
 
import  com.bean.Customer;
 
 
 rule "Binding Param"
    when
       Customer($name:name=="七夜雪")
    then
        System.out.println( "Binding Param Rule and Customer is " + $name );
end


/**java测试代码,采用Junit测试**/
  /**
   * 有文本字段约束的Pattern
   * @throws Exception
   */
    Customer customer = new Customer();
    customer.setName("七夜雪");
    ksession.insert(customer);
    ksession.fireAllRules();

 

  • 字段绑定的Pattern

    Person( $name : name == “bob” )
    变量名称可以是任何合法的java变量,$是可选的,可由于区分字段和变量

    

//drl规则文件
package com.sample
 
import  com.bean.Customer;
 
 rule "Binding Fact"
    when
       $customer:Customer(name=="七夜雪")
    then
        System.out.println( "Binding Fact Rule :"  + $customer );
end
  /**
   * java测试方法
   * 字段绑定的Pattern
   * @throws Exception
   */
  @Test
  public void testBindingParam() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("HaveParam.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    customer.setName("七夜雪");
    ksession.insert(customer);
    ksession.fireAllRules();
    logger.close();
  }
  • Fact绑定的Pattern

    $bob : Person( name == “bob” )字段绑定的Pattern

//drl文件
package com.sample
 
import  com.bean.Customer;
 
 rule "Binding Fact"
    when
       $customer:Customer(name=="七夜雪")  //绑定变量$customer变量名
then 
  System.out.println( "Binding Fact Rule :" + $customer ); 
end

 

  /**
   * Fact绑定的Pattern
   * @throws Exception
   */
  @Test
  public void testBindingFact() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("BindingFact.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    customer.setName("七夜雪");
    customer.setCompany("听雪楼");
    ksession.insert(customer);
    ksession.fireAllRules();
    logger.close();
  }

 

  • 变量约束的Pattern

    Person( name == $name )

package com.sample
 
import  com.bean.Customer;
import  com.bean.Account;
 
 
 rule "Param Limit"
    when
       Customer($name:name=="七夜雪")
       Account(name==$name)
    then
        System.out.println( "Param Limit Rule"  );
end 

  

 /**
   * 变量约束的Pattern
   * @throws Exception
   */
  @Test
  public void testParamLimit() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("ParamLimit.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    customer.setName("七夜雪");
    customer.setCompany("听雪楼");
    Account account = new Account();
    account.setName("七夜雪");
    ksession.insert(customer);
    ksession.insert(account);
    ksession.fireAllRules();
    logger.close();
  }

 

条件元素(Conditional Elements)

    and

  • 对于顶级(非嵌套)patterns是隐式成立的
  • 可以显示add
  • 使用关键字’and’(不推荐使用 &&)
package com.sample
 
import  com.bean.Customer;
import  com.bean.Account;
 
 
 rule "And"
    when
       Customer(name=="七夜雪" ) and
       Account(name=="七夜雪")
    then
        System.out.println( "And Rule"  );
end
 
 
  rule "Default"
    when
       Customer(name=="七夜雪" ) 
       Account(name=="七夜雪")
    then
        System.out.println( "default  is and"  );
end


 rule "&&"
    when
       Customer(name=="七夜雪" ) &&
       Account(name=="七夜雪")
    then
        System.out.println( "And && Rule"  );
end
  /**
   * 条件元素 and、&&,不写默认为and
   * @throws Exception
   */
  @Test
  public void testAndRule() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("And.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    customer.setName("七夜雪");
    Account account = new Account();
    account.setName("七夜雪");
    ksession.insert(customer);
    ksession.insert(account);
    ksession.fireAllRules();
    logger.close();
  }

  

 or

  • 列能被显式or
  • 使用关键字’or’(不推荐使用 ||)

 

package com.sample
 
import  com.bean.Customer;
import  com.bean.Account;
 
 
 rule "Or"
    when
       Customer(name=="七夜雪" ) or
       Account(name=="七夜雪")
    then
        System.out.println( "And Rule"  );
end

  

  /**
   * 条件元素 or,不写默认为and
   * 注:每个条件符合,then的内容都会执行一次
   * @throws Exception
   */
  @Test
  public void testOrRule() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("Or.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    customer.setName("七夜雪");
    Account account = new Account();
    account.setName("七夜雪");
    ksession.insert(customer);
    ksession.insert(account);
    ksession.fireAllRules();
    logger.close();
  }

  

exists 、Not

 

package com.sample
 
import  com.bean.Customer;
import  com.bean.Account;
 
 
 rule "Exists"
    when
       exists Customer()  //工作空间存在customer对象
    then
        System.out.println( "Customer Exists"  );
end


 rule "Not"
    when
      not  Account()  //工作空间不存在Account对象
    then
        System.out.println( "Account Not Exists"  );
 end

  

  /**
   * 条件元素 exist、not,两个刚好相反
   * 
   * @throws Exception
   */
  @Test
  public void testExistsAndNotRule() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("From.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    Account account = new Account();
    account.setName("七夜雪");
    Account account1 = new Account();
    account.setName("碧落");
    customer.getAccounts().add(account);
    customer.getAccounts().add(account1);
    ksession.insert(customer);
    ksession.fireAllRules();
    logger.close();
  }

  from

package com.sample
 
import  com.bean.Customer;
import  com.bean.Account;
 
 
 rule "from"
    when
       $customer:Customer( )
    //customer中的accounts列表中存在name="碧落"的account对象
       Account(name=="碧落") from $customer.accounts 
    then
        System.out.println( "from element test success"  );
end
  /**
   * 条件元素 from
   * 
   * @throws Exception
   */
  @Test
  public void testFromRule() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("From.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    ksession.insert(customer);
    ksession.fireAllRules();
    logger.close();
  }

 

collect

 

package com.sample
 
import  com.bean.Customer;
import  com.bean.Account;
import  java.util.ArrayList;
 
 rule "collect"
    when
       $customer:Customer( )
    //列表中status="Y"的Account对象大于等于4个,
       $accounts:ArrayList(size >= 4) from collect (Account(status == "Y"))
    then
        System.out.println( "collect element test success"  );
end
  /**
   * 条件元素 collect
   * 
   * @throws Exception
   */
  @Test
  public void testCollectRule() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("Collect.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    Account account1 = new Account();
    account1.setStatus("Y");
    Account account2 = new Account();
    account2.setStatus("Y");
    Account account3= new Account();
    account3.setStatus("Y");
    Account account4 = new Account();
    account4.setStatus("Y");
    ksession.insert(customer);
    ksession.insert(account1);
    ksession.insert(account2);
    ksession.insert(account3);
    ksession.insert(account4);
    ksession.fireAllRules();
    logger.close();
  }

 

Accumulate 聚合函数

package com.sample
 
import  com.bean.Customer;
import  com.bean.Account;
 
 rule "accumulate"
    when
    //工作空间中,account对象的num属性之和大于400时符合规则
       $total:Number( intValue > 400)
       from accumulate (Account($num:num),sum($num))
    then
        System.out.println( "accumulate element test success"  );
end
  /**
   * 条件元素 Accumulate
   * 聚合函数
   * @throws Exception
   */
  @Test
  public void testAccumulateRule() throws Exception {
    KnowledgeBase kbase = readKnowledgeBase("Accumulate.drl");
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
    Customer customer = new Customer();
    Account account1 = new Account();
    account1.setNum(100);
    Account account2 = new Account();
    account2.setNum(100);
    Account account3= new Account();
    account3.setNum(100);
    Account account4 = new Account();
    account4.setNum(200);
    ksession.insert(customer);
    ksession.insert(account1);
    ksession.insert(account2);
    ksession.insert(account3);
    ksession.insert(account4);
    ksession.fireAllRules();
    logger.close();
  }

 

你可能感兴趣的:(Droole规则引擎)