Combination mode (Composite pattern)

Source: Internet
Author: User

Combination mode: A set of similar objects as a single object, based on a tree structure to combine objects, to represent parts and the whole hierarchy.

Give an example of managing a company's employees:

 Public classEmployee {PrivateString name; PrivateString Dept; Private Doublesalary; PrivateList<employee>Sub;  PublicEmployee (String n,string D,ints) {name=N; Dept=D; Salary=s; Sub=NewArraylist<employee>(); }     Public voidAdd (Employee e) {sub.add (e); }     Public voidRemove (Emplyee e) {sub.remove (e); }
Public list<employee> getsub () {
return sub;
}
 Public String toString () {        return "name:" + name + "Dept:" + Depr + "Salary:" + salary;   }}

Test code:

Employee CEO =NewEmployee ("A0", "CEO", 30000); Employee headmarketing=NewEmployee ("B0", "Head Marketing", 20000); Employee Clerk1=NewEmployee ("C0", "Marketing", 10000); Employee CLERK2=NewEmployee ("C1", "Marketing", 10000); Employee Headsales=NewEmployee ("B1", "Head Sales", 20000); Employee Sale1=NewEmployee ("C2", "Marketing", 10000); Employee Sale2=NewEmployee ("C3", "Marketing", 10000);    Ceo.add (headmarking); //CEO Management HeadmarkingCeo.add (Headsales);//CEO Management HeadsalesHeadmarking.add (CLERK1); //headmarking Management Two personsHeadmarking.add (CLERK2); Headsales.add (Sale1); //headsales Management Two personsHeadsales.add (sale2);//Print all EmployeesSystem.out.println (CEO); for(Employee e1:CEO.getSub ()) {System.out.println (E1);  for(Employee e2:e1.getSub ()) {System.out.println (E2); }}

The combination mode is suitable for dealing with tree structure problems, such as tree menu, folder file management.

Combination mode (Composite pattern)

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.