23种设计模式----组合模式(Composite Pattern)

组合模式主要用来处理一类具有“容器特征”的对象——即它们在充当对象的同时,又可以作为容器包含其他多个对象。

在这里插入图片描述

public abstract class Shape
{
    public string name;
    public Shape(string name)
    {
        this.name = name;
    }

    public abstract double Area();
    public abstract void display();
}

public class Triangle : Shape
{
    private double _a;
    private double _b;
    private double _c;

    public Triangle(string name,double a, double b, double c) : base(name)
    {
        _a = a;
        _b = b;
        _c = c;
    }

    public override double Area()
    {
        double p = (_a + _b + _c) / 2;
        return Math.Sqrt(p * (p - _a) * (p - _b) * (p - _c));
    }

    public override void display()
    {
        Console.WriteLine("{0} 三条边长:{1},{2},{3},面积:{3}", name, _a, _b, _c, this.Area());
    }
}

public class Rectangle : Shape
{
    private double width;
    private double height;
    public Rectangle(string name,double width,double height) : base(name)
    {
        this.width = width;
        this.height = height;
    }

    public override double Area()
    {
        return width * height;
    }

    public override void display()
    {
        Console.WriteLine("{0} 长:{1},宽:{2},面积:{3}", name, width, height, this.Area());
    }
}	

public class Graphics : Shape
{
    public List<Shape> list = new List<Shape>();

    public Graphics(string name) : base(name)
    {
    }

    public override double Area()
    {
        double sum = 0;
        foreach (Shape child in list)
        {
            sum += child.Area();
        }
        return sum;
    }

    public override void display()
    {
        foreach (Shape child in list)
        {
            child.display();
        }

        Console.WriteLine("{0} 总面积:{1}", name, this.Area());
    }

    public void Add(Shape shape)
    {
        list.Add(shape);
    }

    public void Remove(Shape shape)
    {
        list.Remove(shape);
    }

}

static void Main(string[] args)
    {
        Graphics graphices = new Graphics("全部图形");
        Rectangle rectangle = new Rectangle("矩形",2,3);
        graphices.Add(rectangle);
        Triangle tri = new Triangle("三角形", 2, 3, 4);
        graphices.Add(tri);
        graphices.display();
        Console.Read();

    }

适用以下情形:
  ◊ 希望把对象表示成部分—整体层次结构;
  ◊ 希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中所有对象。
  
特点:
  ◊ 定义了包含基本对象和组合对象的类层次结构。基本对象可以被组合成更复杂的组合对象,而这个组合对象又可以被组合,不断的递归下去。客户代码中,任何用到基本对象的地方都可以使用组合对象;
  ◊ 简化客户代码。客户可以一致地使用组合结构和单个对象。这样用户就不必关心处理的是一个叶子节点还是一个组合组件,从而简化了客户代码;
  ◊ 使得新增类型的组件更加容易。新定义的Composite或Leaf子类自动地与已有的结构和客户代码一起协同工作,客户程序不需因新的Component类而改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值