---
# System prepended metadata

title: Composite
tags: [Design Pattern]

---

---
tags: Design Pattern
---

# Composite

這是我在Design Pattern學到的第一個設計，很實用；舉例來說如果一個繪圖軟體要生成圓形、長方形、三角形以及不規則多邊形，前三者可以簡單地用數學表示，而不規則多邊形則要透過這些基本的形狀去變形相加形成群組而得到，而這個時候就會有個問題，程式碼需要用不同的方式來對待單一元件以及複雜的群組元件，讓程式變得相當複雜；而Composite的目的就是要讓Client 可以用一致的方式看待個體和組成物件！

This is the first design I learned in Design Pattern, and it is very practical; for example, if a drawing software wants to generate circles, rectangles, triangles, and irregular polygons, the first three can be simply expressed mathematically, and irregular polygons Polygons are obtained by deforming and adding these basic shapes to form groups. At this time, there will be a problem. The code needs to treat single components and complex group components in different ways, making the program quite Complex; the purpose of Composite is to allow Clients to see individuals and components in a consistent way!

<font color="#f00">advantage:</font>

1. Easy to add new types of Component

2. For the Client, there is no need to know whether he is dealing with Leaf or Composite

<font color="#f00">disadvantage:</font>

1. Difficulty constraining the number of types of Component in Compoiste

---


![](https://i.imgur.com/RhtoXPv.png)

shape.h
```cpp=
#pragma once

class Shape
{
public:
    virtual ~Shape(){};

    virtual double area() const = 0;

    virtual double perimeter() const = 0;

    virtual std::string info() const = 0;
    
    //for CompoundShape
    virtual void addShape(Shape *shape) {}

    virtual void deleteShape(Shape *shape) {}
};

```

circle.h
```cpp=
//使用 #pragma once 在 ut_circle.h 引用的程式碼這邊就不用再引用一次
#pragma once

class Circle : public Shape
{
public:
    Circle(double radius) : _radius(radius){ }

    double area() const override { }

    double perimeter() const override { }

    std::string info() const override { }  

private:
    double _radius;
};
```

rectangle.h
```cpp=
#pragma once

class Rectangle : public Shape
{
public:
    Rectangle(double length, double width){ }

    double area() const override { }

    double perimeter() const override { }

    std::string info() const override { }  

private:
    double _length;
    double _width;
};
```

compounShape.h
```cpp=
#pragma once
class CompoundShape : public Shape
{
public:
    ~CompoundShape() {}

    double area() const override { }

    double perimeter() const override { }

    std::string info() const override { }

    void addShape(Shape *shape) override { }

    void deleteShape(Shape *shape) override { }

private:
    std::list<Shape *> CompoundShapeList;
};
```

The relevant code is in: https://github.com/andy091045/Design-Pattern/tree/main/posd2021f_110598068_hw03



