“This is the sixth day of my participation in the August More Text Challenge.

Introduction to Combination Mode

Composition pattern is the design idea of combining similar objects or methods into a group of structure-tree objects that can be called.

The combination mode can not only be applied to rule decision tree, but also can be used as service packaging to configure different interfaces in combination, provide external service capabilities and reduce development costs.

The main solution of the composite pattern is a series of simple logical nodes or extended complex logical nodes under different structure organization, for external calls can still be very simple.

Composition pattern structure

  • Component interfaces describe operations common to both simple and complex items in the tree.
  • The leaf node is the basic structure of the tree and contains no subitems. Typically, leaves end up doing most of the real work because they can’t assign work to other parts.
  • A container, also known as a composite, is a unit that contains sub-items such as leaf nodes or other containers. The container does not know the concrete class to which its children belong, and it only interacts with its children through a generic interface. The container receives the request and assigns work to its subprojects, processes the intermediate results, and then returns the final results to the client.
  • The client interacts with all projects through the component interface. Thus, clients can interact with simple or complex items in the tree in the same way.

Application scenarios of the composite mode

  • When a business needs to implement a tree object structure, the composite pattern can be used.

The composite pattern provides two basic element types that share a common interface: simple leaf nodes and complex containers. Containers can contain leaf nodes and other containers. This allows you to build tree-like nested recursive object structures.

  • When you want your client code to handle simple and complex elements in the same way, you can use composite patterns

All elements defined in the composite pattern share the same interface. Thanks to this interface, clients do not have to care about the concrete classes of the objects they use.

The pros and cons of the composite model

Advantages:

1. Complex tree structures can be used more easily using polymorphic and recursive mechanisms

2. The open close principle allows you to add new elements to your application and make them part of the object tree without changing existing code.

Disadvantages:

1. It may be difficult to provide public interfaces for classes that differ greatly in functionality.

implementation

1. Make sure your application’s core model is represented as a tree structure, and try to break it down into simple elements and containers. Where the container must contain both simple elements and other containers.

Declare the component interface and its set of methods that make sense for both simple and complex elements.

3, create a leaf node class to represent a simple element, the program can have multiple different leaf node class.

Create a container class to represent complex elements. In this class, an array member variable is created to store references to its child elements. The array must be able to hold both leaf nodes and containers, so be sure to declare it as a composite interface type.

When implementing component interface methods, remember that the container should delegate most of the work to its children.

Define methods to add and remove child elements in the container.

These operations can be declared in the component interface. Violates the interface isolation principle because these methods in the leaf node class are empty. But you can give clients undifferentiated access to all elements, even those that make up a tree structure.

Demo

/// <summary> // declare common operations for simple and complex objects /// </summary> abstract class Component {public Component() {} /// <summary> /// /// </summary> // <returns></returns> public abstract String Operation(); public virtual void Add(Component component) { throw new NotImplementedException(); } public virtual void Remove(Component component) { throw new NotImplementedException(); } /// </summary> // </summary> /// <returns></returns> public Virtual bool IsComposite() {return true; }}Copy the code
/// </summary> class Leaf:Component {public override string Operation() {return "Leaf"; } public override bool IsComposite() { return false; }}Copy the code
// </summary> class Composite:Component {protected List<Component> _children = new List<Component>(); public override void Add(Component component) { this._children.Add(component); } public override void Remove(Component component) { this._children.Remove(component); } public override string Operation() { int i = 0; String result = "All branches contain those: "; foreach (var component in _children) { result += component.Operation(); if(i! =_children.Count-1) { result += "+"; } i++; } return result + ")"; }}Copy the code
/ / / < summary > / / / / / / Client < summary > class Client {/ / / < summary > / / / component call interface Leaves call / / / < / summary > / / / < param Name ="leaf"></param> public void ClientCode(Component leaf) {console. WriteLine("Result: "+ leaf.operation ()); } /// <summary> // in the base component class, clients can interact with any component, simple and complex objects, // </summary> // <param name=" C1 "></param> // <param name="c2"></param> public void ClientCode2(Component c1,Component c2) { if (c1.IsComposite()) { c1.Add(c2); } the Console. WriteLine (" is the Result: "+ c1. Operation ()); }}Copy the code
class Program { static void Main(string[] args) { Client client = new Client(); Leaf leaf = new Leaf(); Console.WriteLine(" Call leaf......" ); client.ClientCode(leaf); Console.WriteLine("---------------"); Composite tree = new Composite(); Composite branch1 = new Composite(); branch1.Add(new Leaf()); branch1.Add(new Leaf()); Composite branch2 = new Composite(); branch2.Add(new Leaf()); tree.Add(branch1); tree.Add(branch2); Console.WriteLine(" Call complex object......" ); client.ClientCode(tree); Console.WriteLine("---"); client.ClientCode2(tree,leaf); Console.ReadKey(); }}Copy the code

As you can see from the calculation, when only leaves are called the first time, the result will display only leaves, that is, simple elements. When the second declaration instantiates a complex container (including leaves and other containers), the output can also display all leaves and child containers in all containers that declare instances.

In fact, for our business, we need to grasp the logic of the business to see the bottom needs and fit that model, so as not to model code for the model.

Small remarks

Life is short, I don’t want to go after what I can’t see, I just want to catch what I can see.

I am Hui, thank you for reading, if it is helpful to you, please like, forwarding thank you.