Java设计模式<过滤模式>

Java设计模式<过滤模式>

意图

这种模式允许开发人员使用不同的标准来过滤一组对象

场景

在开JDBC开发中经常有这样的场景,需要拼接SQL

代码


public class Person {

    private String name;

    private String sex;

    private float height;

    private float weight;

    public Criteria createCriteria() {
        return new Criteria();
    }

    public static class Criteria {
        protected List criteriaWithoutValue;

        public Criteria() {
            this.criteriaWithoutValue = new ArrayList();
        }

        public void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteriaWithoutValue.add(condition);
        }

        public Criteria andNameIsNotNull() {
            addCriterion(String.format("  NAME IS NOT NULL "));
            return this;
        }

        public Criteria andeightGreaterThan(float height) {
            addCriterion(String.format("   HEIGHT > %s  ",height) );
            return this;
        }

        public String getSql() {
            StringBuffer sb = new StringBuffer("SELECT * FROM  PERSON WHERE ");
            for (int i = 0 ;i

测试类

public class DemoMain {
    public static void main(String[] args) {

        Person p = new Person();
        String sql = p.createCriteria().andNameIsNotNull().andeightGreaterThan(150f).getSql();
        System.err.println(sql);
    }
}

例子中并没有只是单纯的举个例子,结合实际场景才是好用的

你可能感兴趣的:(Java设计模式<过滤模式>)