8
I have a class for tree 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 the previous ones cannot be accessed 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 the creation of Arvore, the only method that can be accessed is AdicionarTronco().
After AdicionarTronco(), only AdicionarGalho() may be accessed, and AdicionarTronco() can no longer be accessed.
Finally, AdicionarFolha() and AdicionarFruto() may be accessed, but may not access other methods.
I need to give the following example of functionality for the class:
(new Arvore())
.AdicionarTronco()
.AdicionarGalho()
.AdicionarFolha()
.AdicionarFruto()
.ImprimirArvore();
For that I thought then of controlling the access to the methods by means of interfaces, and I thought:
public interface IArvore
{
ITronco AdicionarTronco();
void ImprimirArvore();
}
public interface ITronco
{
IGalho AdicionarGalho();
}
public interface IGalho
{
IGalho AdicionarFolha();
IGalho AdicionarFruto();
}
Hence, 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 managed to resolve the issue of not being able to return to the methods, but by Arvore I still have access to the methods AdicionarGalho(), AdicionarFolha() and AdicionarFruto().
Still, in the end I must have access to the method ImprimirArvore().
How can I fix this?
I imagine you’re not really modeling trees in C#. Do you mind giving details about the domain to which this solution would apply?
– user25930
@ctgPi is just a college issue that I was having trouble understanding.
– JamesTK