C # design Pattern (10) -- Composite Pattern)

Source: Internet
Author: User

I. Introduction

During software development, we often encounter situations where simple objects and composite objects are processed. For example, processing directories in the operating system is an example, because directories can contain separate files, folders, and folders, simple objects and composite objects have different functions, as a result, simple objects and composite objects must be distinguished during the operation process, which will lead to unnecessary calls by the customer. However, as a customer, they want to treat simple objects and composite objects consistently. However, the combination mode solves this problem. Next let's take a look at how the combination mode solves this problem.

Ii. detailed introduction to the combination mode 2.1 Definition of the Combination Mode

The combination mode allows you to combine objects into a tree structure to express the "part-whole" hierarchy, so that the customer can process the combination of a single object and an object in a consistent way. The following example shows the combination mode. A graph can be composed of some basic graphic elements, such as a straight line or a circle ), it can also be composed of complex graphics and composed of basic graphics elements). In order to make the customer's calls to the basic and complex graphics consistent, we use the combination mode to achieve the entire purpose.

The most important thing to implement the combination mode is that simple objects and composite objects must implement the same interface. This is why composite objects and simple objects can be processed in composite mode.

2.2 Implementation of combined modes

After introducing the definition of the combination mode, let's use a graphical example to implement the combination mode. The specific code is as follows:

// Construct a graphic tree using some simple graphics and some complex graphics to demonstrate the combination mode. // The Client calls class Client {static void Main (string [] args) {ComplexGraphics complexGraphics = new ComplexGraphics ("a complex image composed of two line segments"); complexGraphics. add (new Line ("Line Segment A"); ComplexGraphics CompositeCG = new ComplexGraphics ("A complex graph composed of A circle and A Line"); CompositeCG. add (new Circle ("Circle"); CompositeCG. add (new Circle ("line B"); complexGraphics. add (CompositeCG); Line l = new Line ("Line Segment C"); complexGraphics. add (l); // graphic Console for displaying complex images. writeLine ("complex drawing:"); Console. writeLine ("---------------------"); complexGraphics. draw (); Console. writeLine ("complex drawing completed"); Console. writeLine ("---------------------"); Console. writeLine (); // remove a component and display the complex Graphic Method complexGraphics. remove (l); Console. writeLine ("after removing a line segment C, draw a complex image as follows:"); Console. writeLine ("---------------------"); complexGraphics. draw (); Console. writeLine ("complex drawing completed"); Console. writeLine ("---------------------"); Console. read () ;}/// <summary> // abstract graph class, /// </summary> public abstract class Graphics {public string Name {get; set ;} public Graphics (string name) {this. name = name;} public abstract void Draw (); public abstract void Add (Graphics g); public abstract void Remove (Graphics g );} /// <summary> // simple Graphics class -- Line // </summary> public class Line: Graphics {public Line (string name): base (name) {}// override the abstract method of the parent class public override void Draw () {Console. writeLine ("painting" + Name);} // because a simple image is added or removed from another image, therefore, the Add or Remove method of a simple image is meaningless. // if the client calls the Add or Remove method of a simple image, an exception will be thrown at runtime. // we can capture this class on the client to Remove and process public override void Add (Graphics g) {throw new Exception ("other images cannot be added to simple graph Line");} public override void Remove (Graphics g) {throw new Exception ("other images cannot be removed from simple graph Line ");}} /// <summary> // simple Graphics class -- Circle // </summary> public class Circle: Graphics {public Circle (string name): base (name) {}// override the abstract method of the parent class public override void Draw () {Console. writeLine ("Draw" + Name);} public override void Add (Graphics g) {throw new Exception ("other images cannot be added to the simple graph Circle ");} public override void Remove (Graphics g) {throw new Exception ("other images cannot be removed from simple Graphics Circle") ;}/// <summary> // complex Graphics, it is composed of some simple graphics. Here we assume that the complex graph consists of a circle and two lines. // </summary> public class ComplexGraphics: graphics {private List <Graphics> complexGraphicsList = new List <Graphics> (); public ComplexGraphics (string name): base (name) {}/// <summary> /// Method of Drawing Complex Images /// </summary> public override void Draw () {foreach (Graphics g in complexGraphicsList) {g. draw () ;}} public override void Add (Graphics g) {complexGraphicsList. add (g);} public override void Remove (Graphics g) {complexGraphicsList. remove (g );}}

Because the Add and Remove methods do not exist for basic graphic objects, the above implementation directly solves this problem by throwing an exception, but we want to solve it in a safer way-because there is no such method for basic graphics, can we remove it? To remove these methods, we have to modify the Graphics interface. We put the method declaration for managing sub-objects in the composite graphic object, in this way, errors occur during compilation when simple objects Line and Circle use these methods. Such an implementation method is called a secure combination mode, however, the above implementation method is called the transparent combination mode. Let's see how the secure combination mode is implemented. The specific implementation code is as follows:

/// Safe combination mode /// the Combination Mode Implemented in this mode declares the method for managing sub-objects in the branches component ComplexGraphics class /// so that if the leaf node Line and Circle are used when the Add or Remove method is enabled, this method solves the problem of transparent combination mode, but it makes the leaf node and the branches component have different interfaces. /// The combination modes implemented by the two methods have their own advantages and disadvantages. You can determine the specific class Client {static void Main (string [] args) based on the actual situation of the problem) {ComplexGraphics complexGraphics = new ComplexGraphics ("a complex image composed of two line segments"); complexGraphics. add (new Line ("Line Segment A"); ComplexGraphics CompositeCG = new ComplexGraphics ("A complex graph composed of A circle and A Line"); CompositeCG. add (new Circle ("Circle"); CompositeCG. add (new Circle ("line B"); complexGraphics. add (CompositeCG); Line l = new Line ("Line Segment C"); complexGraphics. add (l); // graphic Console for displaying complex images. writeLine ("complex drawing:"); Console. writeLine ("---------------------"); complexGraphics. draw (); Console. writeLine ("complex drawing completed"); Console. writeLine ("---------------------"); Console. writeLine (); // remove a component and display the complex Graphic Method complexGraphics. remove (l); Console. writeLine ("after removing a line segment C, draw a complex image as follows:"); Console. writeLine ("---------------------"); complexGraphics. draw (); Console. writeLine ("complex drawing completed"); Console. writeLine ("---------------------"); Console. read () ;}/// <summary> // abstract graph class, /// </summary> public abstract class Graphics {public string Name {get; set ;} public Graphics (string name) {this. name = name;} public abstract void Draw (); // The Add and Remove methods are removed. // The methods used to manage sub-objects are placed in the ComplexGraphics class for management. // These methods only make sense in complex graphics.} // <summary> /// simple graphics class -- Line /// </summary> public class Line: graphics {public Line (string name): base (name) {}// override the parent class abstract method public override void Draw () {Console. writeLine ("painting" + Name) ;}/// <summary> // simple graphics class -- Circle /// </summary> public class Circle: graphics {public Circle (string name): base (name) {}// override the parent class abstract method public override void Draw () {Console. writeLine ("painting" + Name) ;}/// <summary> // complex image, composed of some simple images, assume that the complex graph consists of a circle and two lines. /// </summary> public class ComplexGraphics: graphics {private List <Graphics> complexGraphicsList = new List <Graphics> (); public ComplexGraphics (string name): base (name) {}/// <summary> /// Method of Drawing Complex Images /// </summary> public override void Draw () {foreach (Graphics g in complexGraphicsList) {g. draw () ;}} public void Add (Graphics g) {complexGraphicsList. add (g);} public void Remove (Graphics g) {complexGraphicsList. remove (g );}}

2.3 class diagram of the Combined Mode

After reading the implementation of the above two methods, let's take a look at the class diagram of the combination mode to understand the relationship between classes in the combination mode.

Transparent combination mode class diagram:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/12422955T-0.png "style =" margin: 0px auto; padding: 0px; border: 0px; "alt =" 21132831-30f99887dec34fadb21282f0158f72b "/>

Class diagram of the Safe Combination Mode:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/12422a159-1.png "style =" margin: 0px auto; padding: 0px; border: 0px; "alt =" 21132847-48c4cdf839c84cbeb4ea42d323587e2 "/>

The combination mode involves three roles:

  • Abstract Component) Role: This is an abstract role.GraphicsThis role defines public interfaces and default behaviors for the objects that participate in the combination. It can be used to manage all sub-objects in the transparent combination mode ). In a secure combination mode, the component role does not define a method for managing sub-objects. This definition is provided by the tree branch structure object.

  • Leaf component Leaf) Role: When the leaf object has no sub-object, the above implementation is in progress.Line and CircleAct as this role to define the behavior of the original object that participates in the combination

  • Branch component Composite) Role: Indicates the object with lower-level sub-objects in the combination. The above implementation is in progress.ComplexGraphicsAs this role, the tree branch object provides all methods to Manage Sub-objects, such as Add and Remove.

Iii. Advantages and disadvantages of the Combination Mode

Advantages:

  1. The combination mode allows the client code to process objects and object containers in a consistent manner, without the need to process a single object or a combined object container.

  2. Decouples the customer code from the complex object container structure.

  3. It is easier to add new components to a composite object.

Disadvantages:Makes the design more complex. The client needs to spend more time figuring out the hierarchy between classes. This is a problem for almost all design patterns ).

Notes:

  1. Sometimes the system needs to traverse a sub-component with a tree structure for many times. In this case, you can consider storing the structure of the traversal sub-component in the parent component as a cache.

  2. The client tries not to directly call the methods in the leaf class to implement this on me. It creates a specific object of a tree branch and should useGraphicsComplexGraphics = new ComplexGraphics ("a complex image and a complex image composed of two line segments");), instead, calls are completed using the polymorphism of its parent Graphics class. This increases code reusability.

Iv. application scenarios of the Combination Mode

The combination mode should be considered in the following cases:

  1. The hierarchy of the entire or part of an object.

  2. If 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.

V. Application of the combination mode in. NET

In. the most typical application in. NET is the development of applications, WinForms, and Web. NET Class Library provides many existing controls for these two platforms. windows. forms. dll System. windows. forms. the Control class applies the combination mode, because the Control includes simple controls such as Label and TextBox and composite controls such as GroupBox and DataGrid, each control needs to call the OnPaint method to display the control. To represent the overall and partial hierarchy of the object, microsoft applied the Control class implementation to the combination mode, specifically the transparent combination mode ).

Vi. Summary

The introduction of the combination mode is over. The combination mode decouples the internal structure of the customer program and the complex elements, so that the customer program can process the complex elements just like the simple elements.


This article is from the "LearningHard" blog, please be sure to keep this source http://learninghard.blog.51cto.com/6146675/1312735

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.