Name:Composite
Structure:
Intent:
Combine objects into a tree structure to represent the "part-whole" hierarchy. C o m p o s I t e makes the use of a single object and a composite object consistent.
Applicability:
- The part of the object-the overall hierarchy.
- You want to ignore the differences between a composite object and a single object. You will use all objects in the composite structure in a unified manner.
Instance:
Employee. Java
Package composite_pattern; import Java. util. list; public abstract class employer {public list employers; private string name; Public void setname (string name) {This. name = Name;} Public String getname () {return this. name;} public abstract void add (Employer employer); public abstract void Delete (Employer employer); Public void printinfo () {system. out. println (name);} public list getemployers () {return this. employers ;}}
Programmer. Java
Package composite_pattern; public class programmer extends employer {public Programmer (string name) {setname (name); employers = NULL ;//ProgramMember, indicating no subordinates} public void add (Employer employer) {} public void Delete (Employer employer ){}}
Projectassistant. Java
Package composite_pattern; public class projectassistant extends employer {public projectassistant (string name) {setname (name); employers = NULL; // project assistant, no subordinates} @ overridepublic void add (Employer employer) {}@ overridepublic void Delete (Employer employer ){}}
Projectmanager. Java
Package composite_pattern; import Java. util. arraylist; public class projectmanager extends employer {public projectmanager (string name) {setname (name); employers = new arraylist (); // a large group of people under the Project Manager} public void add (Employer employer) {employee. add (employer);} public void Delete (Employer employer) {employee. remove (Employer );}}
Test. Java
Package composite_pattern; import Java. util. list; public class test {public static void main (string [] ARGs) {employer PM = new projectmanager ("Project Manager "); employer Pa = new projectassistant ("Project Assistant"); employer programmer1 = new Programmer ("Programmer 1"); employer programmer2 = new Programmer ("programmer 2"); PM. add (PA); // Add Project Assistant pm to the project manager. add (programmer2); // Add a programmer 2 list for the Project Manager <employer> EMS = PM. getemployers (); For (Employer EM: EMS) {em. printinfo ();}}}
Conclusion: The combination mode is found online.