Last active
January 13, 2026 22:07
-
-
Save sunmeat/a12e7f18994ce23c7517381912d8537e to your computer and use it in GitHub Desktop.
DIP nice example C#
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
| interface IService | |
| { | |
| void ProvideService(); | |
| } | |
| class PizzaDelivery : IService | |
| { | |
| // ... | |
| public void ProvideService() | |
| { | |
| Console.WriteLine("pizza.od.ua"); | |
| } | |
| } | |
| class Plumber : IService | |
| { | |
| // ... | |
| public void ProvideService() | |
| { | |
| Console.WriteLine("Ремонтую твій бойлер уже третій раз за місяць..."); | |
| } | |
| } | |
| class Electrician : IService | |
| { | |
| // ... | |
| public void ProvideService() | |
| { | |
| Console.WriteLine("Встановлюю нову розетку."); | |
| } | |
| } | |
| class InternetProvider : IService | |
| { | |
| // ... | |
| public void ProvideService() | |
| { | |
| Console.WriteLine("Налаштовую інтернет-підключення."); | |
| } | |
| } | |
| class Person | |
| { | |
| private IService? worker; | |
| public void SelectService(IService injectedWorker) | |
| { | |
| worker = injectedWorker; // низька зв'язаність - прив'язка до типу абстракції | |
| } | |
| public void SolveProblem() | |
| { | |
| if (worker != null) | |
| worker.ProvideService(); | |
| } | |
| } | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| Console.OutputEncoding = System.Text.Encoding.UTF8; | |
| var person = new Person(); | |
| IService service = new Plumber(); | |
| person.SelectService(service); | |
| person.SolveProblem(); | |
| service = new PizzaDelivery(); | |
| person.SelectService(service); | |
| person.SolveProblem(); | |
| service = new Electrician(); | |
| person.SelectService(service); | |
| person.SolveProblem(); | |
| service = new InternetProvider(); | |
| person.SelectService(service); | |
| person.SolveProblem(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment