Overview:
Combines objects into a tree structure to represent a "partial-whole" hierarchy. "Composite makes the user consistent with the use of individual objects and composite objects. ”
Type: Structural mode.
Class Diagram:
Applicability:
1. You want to represent the part of the object-the overall hierarchy.
2. You want users to ignore the difference between a combined object and a single object, and the user will use all the objects in the composite structure uniformly.
Participants:
1.Component
Declares an interface for an object in a composition.
When appropriate, implements the default behavior for all classes of common interfaces.
Declares an interface for accessing and managing component subcomponents.
Optionally, define an interface in the recursive structure to access a parent part and implement it where appropriate.
2.Leaf
The leaf node object is represented in the composition, and the leaf node has no child nodes.
Defines the behavior of a node object in a composition.
3.Composite
Defines the behavior of those parts that have child parts.
Stores the child parts.
Implement operations related to subassemblies in the component interface.
4.Client
An object that manipulates a combined part through the component interface.
Example:
ComponentPublicAbstractClassEmployer {private String name;PublicvoidSetName (String name) {THIS.name = name; }Public StringGetName () {ReturnTHIS.name; }PublicAbstractvoidAdd (employer employer);PublicAbstractvoidDelete (employer employer);public List Employers;PublicvoidPrintinfo () {System.out.println (name);}Public ListGetemployers () {ReturnThis.employers; }}leafPublicClassProgrammerExtendsEmployer {PublicProgrammer (String name) {setName (name); employers =NullProgrammer, means no subordinate.}PublicvoidAdd (Employer employer) {}PublicvoidDelete (Employer employer) {}}PublicClassProjectassistantExtendsEmployer {PublicProjectassistant (String name) {setName (name); employers =NullProject assistant, indicating no subordinates.}PublicvoidAdd (Employer employer) {}PublicvoidDelete (Employer employer) {}}compositePublicClassProjectmanagerExtendsEmployer {PublicProjectmanager (String name) {setName (name); employers =New ArrayList (); }PublicvoidAdd (Employer Employer) {employers.add (employer);}Publicvoiddelete (Employer employer) {employers.remove (employer);}} Client 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 One"); Employer Programmer2 = new Programmer ("Programmer II"); Pm.add (PA); //add programmers to the project manager List EMS = Pm.getemployers (); for (Employer Em:ems) {System.out.println (Em.getname ());}}}
Result
项目助理程序员二
23 Design Modes (19): Combined mode