Last active
January 23, 2026 09:46
-
-
Save sunmeat/f460d1c9c1b71b4765d917d038ba3634 to your computer and use it in GitHub Desktop.
adapter pattern C# example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace AdapterPatternDemo | |
| { | |
| // інтерфейс кухаря | |
| internal interface IChief | |
| { | |
| object MakeBreakfast(); // приготувати сніданок | |
| object MakeLunch(); // приготувати обід | |
| object MakeDinner(); // приготувати вечерю | |
| } | |
| // класи "інструментів сантехніка" | |
| internal class ScrewNut { } // гайка | |
| internal class Pipe { } // шматок труби | |
| internal class Plunger { } // вантуз | |
| // Adaptee - той, кого адаптуємо (сантехнік) | |
| internal class Plumber | |
| { | |
| public object GetScrewNut() => new ScrewNut(); | |
| public object GetPipe() => new Pipe(); | |
| public object GetPlunger() => new Plunger(); | |
| } | |
| // Адаптер: сантехнік видає себе за кухаря | |
| internal class ChiefAdapter : Plumber, IChief | |
| { | |
| public object MakeBreakfast() => GetPlunger(); // на сніданок — вантуз | |
| public object MakeLunch() => GetPipe(); // на обід — труба | |
| public object MakeDinner() => GetScrewNut(); // на вечерю — гайка | |
| } | |
| // клієнт, який хоче смачно поїсти | |
| internal class Client | |
| { | |
| public void Eat(object dish) | |
| { | |
| Console.WriteLine("...Смачного!"); | |
| Thread.Sleep(1200); | |
| } | |
| } | |
| internal static class Program | |
| { | |
| // виклик "швидкої" | |
| private static void CallAmbulanceAsync() | |
| { | |
| Console.WriteLine("Ой-йой! Викликаємо швидку..."); | |
| Console.WriteLine("Не їжте гайки..."); | |
| } | |
| private static void Main() | |
| { | |
| Console.OutputEncoding = System.Text.Encoding.UTF8; | |
| var client = new Client(); | |
| IChief chief = new ChiefAdapter(); | |
| Console.WriteLine("Замовляємо сніданок..."); | |
| client.Eat(chief.MakeBreakfast()); | |
| Console.WriteLine("Замовляємо обід..."); | |
| client.Eat(chief.MakeLunch()); | |
| Console.WriteLine("Замовляємо вечерю..."); | |
| client.Eat(chief.MakeDinner()); | |
| // упс, щось пішло не так… | |
| CallAmbulanceAsync(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment