Created
November 24, 2023 14:12
-
-
Save sunmeat/3e4bacd429a2bafc3112647b74cd3b4d to your computer and use it in GitHub Desktop.
adapter 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
interface IChief | |
{ | |
object MakeBreakfast(); | |
object MakeLunch(); | |
object MakeDinner(); | |
} | |
class ScrewNut { } | |
class Pipe { } | |
class Gasket { } | |
// Adaptee - тот, кого адаптируют | |
class Plumber // сантехник | |
{ | |
public object GetScrewNut() // гайка | |
{ | |
return new ScrewNut(); | |
} | |
public object GetPipe() // кусок трубы | |
{ | |
return new Pipe(); | |
} | |
public object GetGasket() // прокладка | |
{ | |
return new Gasket(); | |
} | |
} | |
// Adapter | |
class ChiefAdapter : Plumber, IChief | |
{ | |
public object MakeBreakfast() | |
{ | |
return GetGasket(); | |
} | |
public object MakeLunch() | |
{ | |
return GetPipe(); | |
} | |
public object MakeDinner() | |
{ | |
return GetScrewNut(); | |
} | |
} | |
// Client | |
class Client | |
{ | |
public void Eat(object dish) | |
{ | |
Console.WriteLine("...Bon Appetit!"); | |
Thread.Sleep(1000); | |
} | |
} | |
class Program | |
{ | |
static void CallAmbulance() | |
{ | |
Console.WriteLine("OOPS!"); | |
// TODO: Add sound playing logic | |
// Console.Beep(); // For simplicity, you can use Console.Beep() for a sound effect | |
// System.Media.SoundPlayer player = new System.Media.SoundPlayer("siren.wav"); | |
// player.Play(); | |
} | |
static void Main() | |
{ | |
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); | |
CallAmbulance(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment