I have a tree class that will have the addition of trunks, branches, leaves and fruits.
I need the class to give access to certain methods only after others and that previous ones can not be access again.
Example:
public class Arvore
{
public List<Membro> Membros { get; set; }
public Arvore AdicionarTronco()
{
Membros.Add(new Tronco());
return this;
}
public Arvore AdicionarGalho()
{
Membros.Add(new Galho());
return this;
}
public Arvore AdicionarFolha()
{
Membros.Add(new Folha());
return this;
}
public Arvore AdicionarFruto()
{
Membros.Add(new Fruto());
return this;
}
public void ImprimirArvore() { ... }
}
So the problem is that after creating Arvore
, the only method that can be accessed is AdicionarTronco()
.
After AdicionarTronco()
, only AdicionarGalho()
can be accessed, and AdicionarTronco()
can no longer be accessed.
Finally, AdicionarFolha()
and AdicionarFruto()
can be accessed but can not access the other methods.
I need to give the following example functionality for the class:
(new Arvore())
.AdicionarTronco()
.AdicionarGalho()
.AdicionarFolha()
.AdicionarFruto()
.ImprimirArvore();
So I thought about controlling access to methods through interfaces, and I thought:
public interface IArvore
{
ITronco AdicionarTronco();
void ImprimirArvore();
}
public interface ITronco
{
IGalho AdicionarGalho();
}
public interface IGalho
{
IGalho AdicionarFolha();
IGalho AdicionarFruto();
}
Then, make the class Arvore
descend from the interfaces:
public class Arvore : IArvore, ITronco, IGalho
{
public List<Membro> Membros { get; set; }
public ITronco AdicionarTronco()
{
Membros.Add(new Tronco());
return this;
}
public IGalho AdicionarGalho()
{
Membros.Add(new Galho());
return this;
}
public IGalho AdicionarFolha()
{
Membros.Add(new Folha());
return this;
}
public IGalho AdicionarFruto()
{
Membros.Add(new Fruto());
return this;
}
public void ImprimirArvore() { ... }
}
But I still managed to solve little.
I have managed to resolve the issue of not being able to get back to the methods, but by Arvore
I still have access to AdicionarGalho()
, AdicionarFolha()
and AdicionarFruto()
methods.
However, in the end I need to access the ImprimirArvore()
method.
How can I resolve this?