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<Account> accounts = new ArrayList<Account>();
  //省略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=="七夜雪")
    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( )
    then
        System.out.println( "Customer Exists"  );
end

 rule "Not"
    when
      not  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( )
       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( )
       $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
       $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();
  }
时间: 2024-10-09 21:20:14

Drools学习笔记2—Conditions / LHS 匹配模式&条件元素的相关文章

Drools学习笔记3—Conditions / LHS—字段约束连接&amp;字段约束操作符

字段约束连接 用于字段约束 对象内部多个约束连接,采用"&&"(and)."||"(or)和","(and) 执行顺序:"&&"(and)."||"(or)和"," 字段约束操作符 >.>=.<.<=.= =.!= contains:包含 A contains B, A中包含B not contains:与contains相反 me

java/android 设计模式学习笔记(12)---组合模式

这篇我们来介绍一下组合模式(Composite Pattern),它也称为部分整体模式(Part-Whole Pattern),结构型模式之一.组合模式比较简单,它将一组相似的对象看作一个对象处理,并根据一个树状结构来组合对象,然后提供一个统一的方法去访问相应的对象,以此忽略掉对象与对象集合之间的差别.这个最典型的例子就是数据结构中的树了,如果一个节点有子节点,那么它就是枝干节点,如果没有子节点,那么它就是叶子节点,那么怎么把枝干节点和叶子节点统一当作一种对象处理呢?这就需要用到组合模式了. 转

java/android 设计模式学习笔记(9)---代理模式

这篇博客我们来介绍一下代理模式(Proxy Pattern),代理模式也成为委托模式,是一个非常重要的设计模式,不少设计模式也都会有代理模式的影子.代理在我们日常生活中也很常见,比如上网时连接的代理服务器地址,更比如我们平时租房子,将找房子的过程代理给中介等等,都是代理模式在日常生活中的使用例子. 代理模式中的代理对象能够连接任何事物:一个网络连接,一个占用很多内存的大对象,一个文件,或者是一些复制起来代价很高甚至根本不可能复制的一些资源.总之,代理是一个由客户端调用去访问幕后真正服务的包装对象

OpenCV学习笔记[5]FLANN特征匹配

OpenCV学习笔记:FLANN特征匹配 本次给出FLANN特征匹配的Java实现. [简介] 特征匹配记录下目标图像与待匹配图像的特征点(KeyPoint),并根据特征点集合构造特征量(descriptor),对这个特征量进行比较.筛选,最终得到一个匹配点的映射集合.我们也可以根据这个集合的大小来衡量两幅图片的匹配程度. 特征匹配与模板匹配不同,由于是计算特征点集合的相关度,转置操作对匹配影响不大,但它容易受到失真.缩放的影响. [特征匹配] FeatureMatching.java: imp

cocos2dx游戏开发——别踩白块学习笔记(二)——经典模式的实现

一.创建GameScene以及GameLayer 就是简单创建一个Scene而已,在此就不多说啦~,可以参照我的打飞机的学习笔记(2). 二.添加一个开始栏 很简单,就是调用Block中的create方法就可以啦~,只是需要传入大小和颜色等等的参数即可. void GameLayer::addStartLine() { auto block = Block::createWithArgs(Color3B::YELLOW, Size(visibleSize.width,visibleSize.he

java/android 设计模式学习笔记(14)---外观模式

这篇博客来介绍外观模式(Facade Pattern),外观模式也称为门面模式,它在开发过程中运用频率非常高,尤其是第三方 SDK 基本很大概率都会使用外观模式.通过一个外观类使得整个子系统只有一个统一的高层的接口,这样能够降低用户的使用成本,也对用户屏蔽了很多实现细节.当然,在我们的开发过程中,外观模式也是我们封装 API 的常用手段,例如网络模块.ImageLoader 模块等.其实我们在开发过程中可能已经使用过很多次外观模式,只是没有从理论层面去了解它. 转载请注明出处:http://bl

java/android 设计模式学习笔记(10)---建造者模式

这篇博客我们来介绍一下建造者模式(Builder Pattern),建造者模式又被称为生成器模式,是创造性模式之一,与工厂方法模式和抽象工厂模式不同,后两者的目的是为了实现多态性,而 Builder 模式的目的则是为了将对象的构建与展示分离.Builder 模式是一步一步创建一个复杂对象的创建型模式,它允许用户在不知道内部构建细节的情况下,可以更精细地控制对象的构造流程.一个复杂的对象有大量的组成部分,比如汽车它有车轮.方向盘.发动机.以及各种各样的小零件,要将这些部件装配成一辆汽车,这个装配过

《大话设计模式》学习笔记系列--1. 简单工厂模式

简单工厂模式实现了一种"工厂"概念的面向对象设计模式,它可以在不指定对象具体类型的情况下创建对象.其实质是定义一个创建对象的接口,但让实现这个接口的类来决定实例化具体类.工厂方法让类的实例化推迟到子类中进行. 以书本上的计算器程序为例,其UML描述如下: 图中,AddOperator, SubtactOpertor继承算式基类Operator,而CreateOperator则是负责创建一个操作类,而不指明具体的子类类型. 下面,我们来看代码: 首先操作积累: /// <summa

java/android 设计模式学习笔记(16)---命令模式

这篇博客我们来介绍一下命令模式(Command Pattern),它是行为型设计模式之一.命令模式相对于其他的设计模式更为灵活多变,我们接触比较多的命令模式个例无非就是程序菜单命令,如在操作系统中,我们点击关机命令,系统就会执行一系列的操作,如先是暂停处理事件,保存系统的一些配置,然后结束程序进程,最后调用内核命令关闭计算机等,对于这一系列的命令,用户不用去管,用户只需点击系统的关机按钮即可完成如上一系列的命令.而我们的命令模式其实也与之相同,将一系列的方法调用封装,用户只需调用一个方法执行,那