Composite Pattern

Introduction and Implementation of Composite Pattern


Category: Design Patterns Tags: C#


Introduction

        Composite Pattern is another Structural Design Pattern which let us treat single object and group of objects in same way. means no need to write different implementations for single and composite objects. It can be understood by a tree where we have leaf node and branch node and both can be treated in same way.

Implementation

        To understand Composite Pattern we will create an interface IComputer with a method Print that prints whether computer is a laptop or desktop, we will implement the method in subclsses:

interface IComputer
{
    void Print();
}
class Laptop : IComputer
{
    public void Print()
    {
        Console.WriteLine("Laptop");
    }
}
class Desktop : IComputer
{
    public void Print()
    {
        Console.WriteLine("Desktop");
    }
}

Now we will create composite class which will hold composition of IComputer class and provides some extra methods to manipulate this composition:

class CompositeComputer : IComputer
{
//Composition
List<IComputer> computers = new List<IComputer>();
//Additional methods
public void Add(IComputer computer)
{
computers.Add(computer);
}
public void AddRange(params IComputer[] computer)
{
computers.AddRange(computer);
}
public void Remove(IComputer computer)
{
computers.Remove(computer);
}
//Implements from interface
public void Print()
{
foreach (IComputer computer in computers)
{
computer.Print();
}
}
}

Above class is composition class which has composite type and implements some methods like Add, Remove and Implements Print. Now let's execute this code:

CompositeComputer computer = new CompositeComputer();
CompositeComputer computer1 = new CompositeComputer();
computer1.Add(new Laptop());
computer.Add(new Desktop());
computer.Add(new Desktop());
computer.Add(new Laptop());
computer.Add(computer1);
computer.Print();

Above code adds desktop, laptop as well composite type in list and print all of them using same method, output:

 

Desktop

Desktop

Laptop

Laptop


Like 0 People
Last modified on 16 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 132
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x