C # Design Pattern--Combined mode

Source: Internet
Author: User

First, the combination mode introduction:

The combined mode decouples the internal structure of the client and complex elements, allowing the client program to handle complex elements as simple elements. Allows you to combine objects into a tree structure to represent a "part-to-whole" hierarchy, allowing customers to handle a single object and the combination of objects in a consistent manner. The most critical place to implement a composite pattern is that simple objects and composite objects must implement the same interface.

Second, the design background:

In the software development process, we often encounter the processing of simple objects and composite objects, such as the processing of directories in the operating system is an example, because the directory can include a separate file (such as Word, TXT, Excel), can also include folders, folders are composed of files, Because simple objects and composite objects differ functionally, it is necessary to differentiate between simple objects and compound objects during the operation, which can lead to unnecessary inconvenience to customer invocation, but as a customer, they want to be able to consistently treat simple objects and composite objects, but the combinatorial pattern is to solve such problems. Let's take this example to see the implementation of the combinatorial pattern.

Third, the relevant code:

1. create file abstract class

    /// <summary>    ///file abstract class/// </summary>     Public Abstract classFile { Public stringName {Get;Set; }  PublicFile (stringname) {             This. Name =name; }         Public Abstract voidNew ();  Public Abstract voidaddfile (file file);  Public Abstract voiddeletefile (file file); }

2. Create a concrete Simple object class (Simple Object): Word document class and Excel document class

    /// <summary>    ///specific Simple Object class--word document file/// </summary>     Public classWord:file { PublicWord (stringName):Base(name) {} Public Override voidNew () {Console.WriteLine ("To create a new Word document:"+Name); }        //because the file is the smallest unit of the directory, the file cannot be created under the file, so the AddFolder and Removefolder methods in the Simple object Word document file class have no meaning         Public Override voidaddfile (file file) {Throw NewException ("You cannot create a file to a Word file"); }         Public Override voiddeletefile (file file) {Throw NewException ("You cannot delete a file from a Word file"); }    }
    /// <summary>    ///specific Simple Object class--excel document file/// </summary>     Public classExcel:file { PublicExcel (stringName):Base(name) {} Public Override voidNew () {Console.WriteLine ("Create a new Excel document:"+Name); }         Public Override voidaddfile (file file) {Throw NewException ("You cannot create a file to an Excel file"); }         Public Override voiddeletefile (file file) {Throw NewException ("You cannot delete files from an Excel file"); }    }

3. Create a folder Class (Composite object):

    /// <summary>    ///folder class, composed of some files/// </summary>     Public classFolder:file {PrivateList<file> file_list =NewList<file>();  PublicFolder (stringName):Base(name) {}/// <summary>        ///folders to create various files/// </summary>         Public Override voidNew () {foreach(varIteminchfile_list) {Item.            New (); }        }         Public Override voidaddfile (file file) {file_list.        ADD (file); }                 Public Override voiddeletefile (file file) {file_list.        Remove (file); }    }

4. Call

        Static voidMain (string[] args) {Folder Folder=NewFolder ("a folder and a Word document that make up a folder"); Folder. AddFile (NewWord ("I am a Word document 1")); Folder Folder2=NewFolder ("a Word document and a folder that consists of an Excel document"); Folder2. AddFile (NewWord ("I am a Word document 2")); Folder2. AddFile (NewExcel ("I am an Excel document 1")); Folder.            AddFile (Folder2); Excel Excel=NewExcel ("I am an Excel document 2"); Folder.            AddFile (Excel); //View Foldersfolder.            New ();            Console.readkey (); //remove a file and view the folderfolder.            DeleteFile (Excel); Folder.            New ();        Console.readkey (); }

The above implementation is called the transparent combination mode, because the basic file object does not exist AddFile and DeleteFile method, the above implementation directly by throwing an exception to solve the problem, but we want to solve in a more secure way-- Because the basic file does not exist at all, can we remove the methods? In order to remove these methods, we have to modify the file interface, we put the method declaration of the management sub-object inside the folder object , so that Simple object Word, Excel use these methods when compiling error, such an implementation of the way we call the security of the combined mode. The specific code is as follows:

    /// <summary>    ///folder class, composed of some files/// </summary>     Public classFolder:file {PrivateList<file> file_list =NewList<file>();  PublicFolder (stringName):Base(name) {}/// <summary>        ///folders to create various files/// </summary>         Public Override voidNew () {foreach(varIteminchfile_list) {Item.            New (); }        }         Public voidaddfile (file file) {file_list.        ADD (file); }                 Public voiddeletefile (file file) {file_list.        Remove (file); }    }

Iv. three roles for combination mode:

    • abstract Component (Component) role : This is an abstract role in which File serves as the role, and in a transparent combination pattern, it defines the common interface and default behavior of the participating objects, which can be used to manage the child objects. In the safe combination mode, the component role does not define the method of managing the sub-object, which is given by the branch structure object.
    • Leaf component (leaf) role : A leaf object when there are no subordinate child objects, the above implementation in Word and Excel act as this role, define the behavior of the original object to participate in the composition
    • Branch Component (Composite) Role : Represents an object that participates in a group of subordinate sub-objects, in which the folder acts as the role, and the tree object gives all the method implementations that manage the child objects, such as AddFile, DeleteFile, and so on.

V. Use of the scene:

    1. You need to represent the whole or part of an object hierarchy.
    2. If you want users to ignore the combination object and the individual object, the user will use all the objects in the composite structure uniformly.

Vi. Summary:

Advantages:

    1. The combined pattern enables client code to handle objects and object containers consistently, without the need for a single object for relational processing, or as a combined object container.
    2. Decouple the customer code from the complex object container structure.
    3. New artifacts can be added to the composition object more easily.

Disadvantages:

    1. Make the design more complex. The client needs to spend more time clearing the hierarchy between classes.

C # Design Pattern--Combined mode

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.