Previous | Home | Next |
The composite pattern is used to represent the object with the tree structure. suppose that in a School multiple student in a hierarchy order. in this order the principle has its subordinates, and the Teacher is subordinates but student has no subordinate.
- Composite Pattern is more flexible than the compared to the static inheritance.
- It is simplify to coding by implementing every feature in a class.
- It enhances the capability of an object as the new classes are created to add new features and make some changes.
The Composite Pattern is used when the object is responsible to be added to the individual objects dynamically without affecting other objects. Where an object's responsibilities may vary from time to time. Now, lets try to solve the above problem technically.
Develop a class "Student" having the getters and setters for the attributes stuname, stumark and principle subordinates.
Example
// Create the Student class package r4r; public class student { String stuname; double stumark; student(String n, double s){ stuname = n; stumark = s; } String getName() { return stuname; } double getMark() { return stumark; } public String toString() { return "Student" + stuname; } } //Create the Principle class package r4r; public class principle { principle prin; student[] stu; String dept; principle(principle prin,student[] e, String d ) { this(e, d); this.prin = prin; } principle(student[] e, String d) { stu = e; dept =d; } String getDept() { return dept; } principle getPrinciple() { return prin; } student[] getStudent() { return stu; } public String toString() { return dept + " principle"; } } // Create the Main class package r4r; public class compositetest { public static void main(String[] args) { student[] s1 = {new student("Sumit", 90), new student("Amitab", 80)}; principle p1 = new principle(s1, "M. Singh"); student[] s2 = {new student("Suman", 60), new student("Ravindra", 50), new student("Vinay", 60)}; principle p2 = new principle(p1, s2, "Rules"); System.out.println(p2); student[] stu = p2.getStudent(); Object stu1; if (stu != null) for (int k = 0; k < stu.length; k++) System.out.println(" "+stu[k]+" Mark:"+ stu[k].getMark()); principle p = p2.getPrinciple(); String p3; System.out.println(" " + p); if (p1!= null) { student[] stus = p.getStudent(); if (stus != null) for (int k = 0; k < stus.length; k++) System.out.println(" " + stus[k]+" Mark:"+ stus[k].getMark()); } } }
Previous | Home | Next |