Kompozyt
unknown
csharp
2 years ago
2.5 kB
12
Indexable
using System; using System.Collections.Generic; using System.Xml.Serialization; public interface Kompozyt { // void Renderuj(); void DodajElement(Kompozyt element); void UsunElement(Kompozyt element); } public class Lisc : Kompozyt { public string nazwa { get; set; } public Lisc(string nazwa) { this.nazwa = nazwa; } public void DodajElement(Kompozyt element) { throw new Exception("Obiekt Liść nie może mieć dzieci."); } public void Renderuj() { Console.WriteLine($"Liść {nazwa} renderowanie..."); } public void UsunElement(Kompozyt element) { throw new NotImplementedException(); } // konstruktor // 2 brakujące metody których wymaga interfejs } public class Wezel : Kompozyt { private List<Kompozyt> Lista = new List<Kompozyt>(); public string nazwa { get; set; } public Wezel(string nazwa) { this.nazwa = nazwa; } public void DodajElement(Kompozyt element) { Lista.Add(element); } public void UsunElement(Kompozyt element) { if (Lista != null && Lista.Count > 0) Lista.Remove(element); } // 2 brakujące metody public void Renderuj() { //rozpoczęcie renderowania Console.WriteLine($"{nazwa} rozpoczęcie renderowania"); //foreach item.Renderuj(); foreach (var item in Lista) { item.Renderuj(); } Console.WriteLine($"{nazwa} zakończenie renderowania"); //zakończenie renderowania } } class MainClass { public static void Main(string[] args) { // // definicje struktury // Kompozyt korzen = new Wezel("Korzeń"); Kompozyt wezel2 = new Wezel("Węzeł 2"); Kompozyt wezel3 = new Wezel("Węzeł 3"); Kompozyt wezel3_3 = new Wezel("Węzeł 3.3"); korzen.DodajElement(new Lisc("1.1")); wezel2.DodajElement(new Lisc("2.1")); wezel2.DodajElement(new Lisc("2.2")); wezel2.DodajElement(new Lisc("2.3")); wezel3.DodajElement(new Lisc("3.1")); wezel3.DodajElement(new Lisc("3.2")); wezel3.DodajElement(wezel3_3); wezel3_3.DodajElement(new Lisc("3.3.1")); korzen.DodajElement(wezel2); korzen.DodajElement(wezel3); korzen.Renderuj(); } }
Editor is loading...
Leave a Comment