Created
May 27, 2024 08:30
-
-
Save sunmeat/f460d1c9c1b71b4765d917d038ba3634 to your computer and use it in GitHub Desktop.
adapter pattern C# example
This file contains 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
using System.Media; | |
using System.Net; | |
using System.Runtime.InteropServices; | |
interface IChief | |
{ | |
object MakeBreakfast(); | |
object MakeLunch(); | |
object MakeDinner(); | |
} | |
class ScrewNut { } | |
class Pipe { } | |
class Plunger { } | |
// Adaptee - тот, кого адаптируют | |
class Plumber // сантехник | |
{ | |
public object GetScrewNut() // гайка | |
{ | |
return new ScrewNut(); | |
} | |
public object GetPipe() // кусок трубы | |
{ | |
return new Pipe(); | |
} | |
public object GetPlunger() // вантус | |
{ | |
return new Plunger(); | |
} | |
} | |
// Adapter | |
class ChiefAdapter : Plumber, IChief | |
{ | |
public object MakeBreakfast() | |
{ | |
return GetPlunger(); | |
} | |
public object MakeLunch() | |
{ | |
return GetPipe(); | |
} | |
public object MakeDinner() | |
{ | |
return GetScrewNut(); | |
} | |
} | |
// заказчик банкета :) | |
class Client | |
{ | |
public void Eat(object dish) | |
{ | |
Console.WriteLine("...Bon Appetit!"); | |
Thread.Sleep(1000); | |
} | |
} | |
class Program | |
{ | |
static async Task CallAmbulanceAsync() | |
{ | |
Console.WriteLine("OOPS!"); | |
string audioUrl = "http://sunmeat.atwebpages.com/siren.wav"; | |
string tempFilePath = Path.GetTempFileName(); // временный файл для сохранения аудио | |
using (var client = new WebClient()) // да, веб-клиент устаревший )) но кода на HttpClient будет в 3 раза больше :) | |
{ | |
await client.DownloadFileTaskAsync(audioUrl, tempFilePath); // скачиваем аудиофайл | |
} | |
using (var player = new SoundPlayer(tempFilePath)) | |
{ | |
player.Play(); | |
Console.WriteLine("Оёёй..."); | |
Console.ReadKey(true); | |
player.Stop(); | |
} | |
// удаляем временный файл после использования | |
File.Delete(tempFilePath); | |
} | |
static void Main(string[] args) | |
{ | |
Console.Title = "Adapter Pattern Example"; | |
Client client = new Client(); | |
IChief chief = new ChiefAdapter(); | |
object dish = chief.MakeBreakfast(); | |
client.Eat(dish); | |
dish = chief.MakeLunch(); | |
client.Eat(dish); | |
dish = chief.MakeDinner(); | |
client.Eat(dish); | |
_ = CallAmbulanceAsync(); | |
Thread.Sleep(10000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment