The six------combination mode and filter mode of the Advanced Java design pattern

Source: Internet
Author: User
Objective

In the previous article, we studied the appearance pattern and adorner mode of the structural pattern. This article is to learn the combination mode and filter mode.

Combination mode

Brief introduction

The combination pattern is used to treat a similar set of objects as a single object. The combined pattern combines objects based on a tree structure to represent parts and the overall hierarchy. This type of design pattern is a structured pattern that creates a tree structure of object groups.

In simple terms, a similar object is grouped according to the tree structure, and then the part is used to do what. A <大话设计模式> very vivid example of this is the file system in the computer.

The file system consists of directories and files. Each directory can be loaded with content. The contents of a directory can be either a file or a directory. In this way, the computer's file system is organized in a recursive structure.

Of course, here we can also use a simple example to explain the composition mode.

In the school, there are many students, but these students have different identities, some students are the president of the student Union, some members of the student union, some monitor, some sports committee, and so on, of course, most of them are ordinary students, and did not assume other posts. In this case, we can use the combination mode to combine.

According to management, the largest student position is the president of the Students ' Union, the president of the Student Council has a student council member, and then the Student Council and the management of ordinary students, they are independent of each other, can become a part, can eventually become a whole. It can be said that it fits perfectly in the combined pattern 树形结构以表示‘部分-整体’的层次结构 .

Nonsense is not much to say, the following code development.
First, define a student class, with the student's name and position attributes.
Then add the Add (), remove (), get () methods in the student class, and finally make the hierarchy call.

code example:

Class student{private String name;        private String position;    Private list<student> students;        Public Student (string name, string position) {this.name = name;        This.position = position;    Students=new arraylist<student> ();    } public void Add (Student Student) {students.add (Student);    } public void Remove (Student Student) {students.remove (Student);    } public list<student> get () {return students;    } @Override Public String toString () {return "Student [name=" + name + ", position=" + position + "]"; }}public class Compositetest {public static void main (string[] args) {Student studentleader=new Student ("        Xiao Ming, "President of the Student Union");                Student committeemember=new Student ("Xiao Gang", "Student council member");                Student student=new Student ("Xiao Hong", "student");        Committeemember.add (student);                Studentleader.add (Committeemember); System.out.println ("-" +studentleader);            Studentleader.get (). ForEach (sl->{System.out.println ("--" +SL);            Sl.get (). ForEach (cm->{System.out.println ("---" +cm);        });    }); }}

Output Result:

    -Student [name=小明, position=学生会主席]    --Student [name=小刚, position=学生会委员]    ---Student [name=小红, position=学生]

In the above example, we have added three students (much the same, mainly thinking), in the school to play the president of the Student Union, Student council members and students. Among them, the President of the Student Council manages the student council members, the students ' Council members, they belong to a hierarchical relationship, a layer of inclusion. In this, we also found that, in fact, the combination mode is to put an object to contain another object, and then through a combination of ways to do some layout.

Advantages of the combined mode:

High-level module calls are simpler, and adding a node is convenient.

Disadvantages of the combined mode:

Because the declaration of its child nodes is an implementation class, not an interface, it violates the dependency inversion principle.

Usage scenarios:
can be represented as a ' part-whole ' hierarchy.

Filter mode

Brief introduction

The filter pattern allows developers to use different criteria to filter a set of objects and connect them in a decoupled way through logical operations. This type of design pattern is a structured model that combines multiple criteria to obtain a single standard.

In simple terms, the function of the pattern is to do a filter as its name. We are generally in the background of the development of the interface, we will filter out some requests. In fact, the main implementation of the filter mode is also this function, nonsense not much to say, began to use the code to explain the corresponding.

Here still with the students to explain, the school students have boys and girls, schools have different grades, when we compare the information of students, you can use the filter mode to be grouped. For example, the number of boys in the school, the number of girls in the first year, the number of third-year students or girls, and so on.

code example:
Since the code is a bit more, here is a separate explanation.
First, define an entity class with three attributes, name, gender, and grade.

class Student{    private String name;     private String gender;     private Integer grade;    public Student(String name, String gender, Integer grade) {        super();        this.name = name;        this.gender = gender;        this.grade = grade;    }        public String getName() {        return name;    }        public void setName(String name) {        this.name = name;    }        public String getGender() {        return gender;    }        public void setGender(String gender) {        this.gender = gender;    }        public Integer getGrade() {        return grade;    }        public void setGrade(Integer grade) {        this.grade = grade;    }    @Override    public String toString() {        return "Student [name=" + name + ", gender=" + gender + ", grade=" + grade + "]";    }}

Then define a common interface that specifies the method of implementation.

interface FilterinGrule {    List<Student>  filter(List<Student> students);}

The

then implements the interface and formulates different filtering rules. Here are mainly three kinds of rules, ordinary filtering, and filtering, or filtering. The
is implemented in the following ways:

Class Malestudents implements filteringrule{@Override public list<student> filter (list<student> Student         s) {list<student> malestudents = new arraylist<student> (); Students.foreach (student->{if (Student.getgender (). Equalsignorecase ("male")) {malestudents.             Add (student);        }        });    return malestudents; }}class Femalestudents implements filteringrule{@Override public list<student> filter (list<student> stu         Dents) {list<student> femalestudents = new arraylist<student> (); Students.foreach (student->{if (Student.getgender (). Equalsignorecase ("female")) {Femalestude             Nts.add (student);        }        });    return femalestudents; }}class Secondgrade implements filteringrule{@Override public list<student> filter (list<student> Studen TS) {list<student> secondgradestudents = new ArrayList<student> ();             Students.foreach (student->{if (student.getgrade () = = 2) {Secondgradestudents.add (student);                }        });    return secondgradestudents;     }}class and implements filteringrule{private Filteringrule filter;         Private Filteringrule Filter2;         Public and (Filteringrule Filter,filteringrule filter2) {this.filter=filter;     This.filter2=filter2; } @Override Public list<student> filter (list<student> students) {list<student> Student        S2=filter.filter (students);    Return Filter2.filter (STUDENTS2);     }}class Or implements filteringrule{private Filteringrule filter;         Private Filteringrule Filter2;         Public Or (Filteringrule filter,filteringrule filter2) {this.filter=filter;     This.filter2=filter2; } @Override Public list<student> filter (list<student> students) {list<student> sTudents1=filter.filter (students);        List<student> Students2=filter2.filter (students);             Students2.foreach (student->{if (!students1.contains (student)) {Students1.add (student);        }        });    return students1; }}

The

Finally comes back to the call test, adds some students, and assigns gender and class. The filter is then based on different conditions.

public class Filtertest {public static void main (string[] args) {list<student> list=new Arraylist<stu        Dent> ();        List.add (New Student ("Xiaoming", "Male", 1));        List.add (New Student ("Little Red", "female", 2));        List.add (New Student ("Xiao Gang", "Male", 2));        List.add (New Student ("Little Chardonnay", "female", 3));        List.add (New Student ("Small Wisdom", "Male", 3));                        List.add (New Student ("nothingness", "male", 1));        Filteringrule male = new malestudents ();        Filteringrule female = new femalestudents ();        Filteringrule Secondgrade = new Secondgrade ();        Filteringrule Secondgrademale = new and (secondgrade, male);                Filteringrule Secondgradeorfemale = new Or (secondgrade, female);        System.out.println ("Boys:" +male.filter (list));        System.out.println ("Female:" +female.filter (list));        System.out.println ("Sophomore:" +secondgrade.filter (list));        System.out.println ("Second grade Boys:" +secondgrademale.filter (list)); System.out.println ("TwoGrade students or Girls: "+secondgradeorfemale.filter (list)"); }}

Output Result:

男生:[Student [name=小明, gender=male, grade=1], Student [name=小刚, gender=male, grade=2], Student [name=小智, gender=male, grade=3], Student [name=虚无境, gender=male, grade=1]]女生:[Student [name=小红, gender=female, grade=2], Student [name=小霞, gender=female, grade=3]]二年级学生:[Student [name=小红, gender=female, grade=2], Student [name=小刚, gender=male, grade=2]]二年级男生:[Student [name=小刚, gender=male, grade=2]]二年级的学生或女生:[Student [name=小红, gender=female, grade=2], Student [name=小刚, gender=male, grade=2], Student [name=小霞, gender=female, grade=3]]

Through the above example, we find that the filter pattern is very simple, make the filter rules, and then filter according to the standards set, to get the data that meet the criteria. The filter pattern is simple, but it's a bit cumbersome to build filtering rules, but after jdk1.8, we can use stream flow to make rules more convenient (this is left to be said later).

Advantages of Filter Mode:

Simple, decoupled, easy to use.

Disadvantages of Filter Mode:

There seems to be no ...

Usage scenarios:

When a filter is required.

Other music recommendations

Actually listen to the music and read the blog very enjoy ~_~

Original is not easy, if feel good, hope to give a recommendation! Your support is my greatest motivation for writing!
Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.