Essentially in a composite pattern you would need three classes. One would be the treenode and the other two would inherit from that. One would be a project capable of holding children. The other would be a child/leaf node and would be the individual Custos.
When you use the classes you would create a new Projectos and add child nodes, then call the Display method when you wanted them to display. You could obviously add logic for other functions. This is similar to code found here: http://www.dofactory.com/net/composite-design-pattern
Usage might be
Main
Projectos project = new Projectos("Projetos");
project.Add(new Custos("Arquitetura", 15, 70.00);
Projectos electricos = new Projectos("Electricos");
electricos.Add(new Custos("custo1", 20, 80.00);
project.Add(electricos);
project.Display();
Projectos
using System;
using System.Collections.Generic;
namespace CompositePatternExercise
{
class Projectos : CustosNode
{
private List<CustosNode> elements = new List<CustosNode>();
// Constructor
public Projectos(string name) : base(name)
{
}
public override void Add(CustosNode d)
{
elements.Add(d);
}
public override void Remove(CustosNode d)
{
elements.Remove(d);
}
public override void Display()
{
decimal totalValue = 0;
decimal totalAmount = 0;
Console.WriteLine(_name);
// Display each child element on this node
foreach (CustosNode d in elements)
{
d.Display();
totalAmount += d.Amount;
totalValue += d.Value;
}
Console.Write("Project total:" + totalAmount.ToString("C") + " " + totalAmount.ToString("C"));
}
}
}
Custos
namespace CompositePatternExercise
{
class Custos : CustosNode
{
// Constructor
public Custos(string name, decimal amount, decimal value) : base(name, amount, value)
{
}
public override void Add(CustosNode c)
{
Console.WriteLine(
"Cannot add to a custo");
}
public override void Remove(CustosNode c)
{
Console.WriteLine(
"Cannot remove from a custo");
}
public override void Display()
{
Console.WriteLine(_name + " " + Amount.ToString("C") + " " + Value.ToString("C"));
}
}
}
}
CustosNode
namespace CompositePatternExercise
{
abstract class CustosNode
{
protected string _name;
protected decimal _amount = 0m;
protected decimal _value = 0m;
public decimal Value { get => _value; }
public decimal Amount { get => _amount; }
// Constructor
public CustosNode(string name)
{
this._name = name;
}
public CustosNode(string name, decimal amount, decimal value)
{
this._name = name;
this._amount = amount;
this._value = value;
}
public abstract void Add(CustosNode c);
public abstract void Remove(CustosNode c);
public abstract void Display();
}
}