Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revision | |||
statnice:bakalar:b6b36omo [2025/06/13 07:24] – [Creational design patterns: factory a abstract factory, builder, prototype, singleton, dependency injection] prokop | statnice:bakalar:b6b36omo [2025/06/13 07:31] (current) – [Structural design patterns: adapter, proxy, bridge, composite, facade, decorator, flyweight] prokop | ||
---|---|---|---|
Line 582: | Line 582: | ||
{{statnice: | {{statnice: | ||
+ | |||
+ | === Composite Design Pattern === | ||
+ | |||
+ | * Účel: | ||
+ | * Umožňuje jednotné zacházení s **jednotlivými objekty** i s **jejich složením (stromová struktura)**. | ||
+ | * Používá se pro reprezentaci **hierarchických struktur** (např. souborový systém, GUI komponenty, organizace). | ||
+ | |||
+ | * Struktura: | ||
+ | * **Component** – společné rozhraní pro listy i složené objekty. | ||
+ | * **Leaf** – jednoduchý objekt (např. soubor). | ||
+ | * **Composite** – složený objekt (např. složka obsahující další objekty). | ||
+ | |||
+ | * Výhody: | ||
+ | * Rekurzivní zpracování hierarchických struktur. | ||
+ | * Klientský kód se nemusí starat, zda pracuje s listem nebo composite – volá jednotné metody. | ||
+ | * Umožňuje dynamicky přidávat/ | ||
+ | |||
+ | === Příklad použití: souborový systém === | ||
+ | |||
+ | <code java> | ||
+ | interface FileSystemItem { | ||
+ | void display(String indent); | ||
+ | } | ||
+ | |||
+ | class File implements FileSystemItem { | ||
+ | private String name; | ||
+ | |||
+ | public File(String name) { | ||
+ | this.name = name; | ||
+ | } | ||
+ | |||
+ | public void display(String indent) { | ||
+ | System.out.println(indent + "- File: " + name); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | class Folder implements FileSystemItem { | ||
+ | private String name; | ||
+ | private List< | ||
+ | |||
+ | public Folder(String name) { | ||
+ | this.name = name; | ||
+ | } | ||
+ | |||
+ | public void add(FileSystemItem item) { | ||
+ | children.add(item); | ||
+ | } | ||
+ | |||
+ | public void display(String indent) { | ||
+ | System.out.println(indent + "+ Folder: " + name); | ||
+ | for (FileSystemItem item : children) { | ||
+ | item.display(indent + " | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | |||
+ | public class CompositeDemo { | ||
+ | public static void main(String[] args) { | ||
+ | Folder root = new Folder(" | ||
+ | root.add(new File(" | ||
+ | |||
+ | Folder src = new Folder(" | ||
+ | src.add(new File(" | ||
+ | src.add(new File(" | ||
+ | |||
+ | root.add(src); | ||
+ | root.display("" | ||
+ | } | ||
+ | } | ||
+ | </ | ||
=== Decorator === | === Decorator === |