简体   繁体   中英

What is 'composite pattern'?

任何人都可以解释并给出复合设计模式的真实示例吗?

The composite pattern can be used when a collection of objects should be treated the same way as one object of the same type. This is often used with tree-structured data. Below is an example where this pattern suits well:

public abstract class Shape {
    public abstract void Draw();
}

public class Line : Shape {
    public override void Draw() {
        // Draw line
    }
}

public class Polygon : Shape {

    private IList<Line> lines;

    public override void Draw() {
        foreach (Shape line in lines) {
            line.Draw();
        }
    }
}

As you can see, the pattern makes it possible for the code dealing with drawing shapes to be unaware of how many lines are drawn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM