-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
88 lines (76 loc) · 2.33 KB
/
Program.cs
File metadata and controls
88 lines (76 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
namespace Adapter;
// Target interface that client expects
public interface IMediaPlayer
{
void Play(string audioType, string fileName);
}
// Adaptee - Advanced player with different interface
public class AdvancedMediaPlayer
{
public void PlayMp4(string fileName)
{
Console.WriteLine($"Playing MP4 file: {fileName}");
}
public void PlayVlc(string fileName)
{
Console.WriteLine($"Playing VLC file: {fileName}");
}
}
// Adapter - Makes AdvancedMediaPlayer compatible with IMediaPlayer
public class MediaAdapter(string audioType) : IMediaPlayer
{
// Using C# 14 field keyword
private AdvancedMediaPlayer AdvancedPlayer { get; init; } = new AdvancedMediaPlayer();
public void Play(string audioType, string fileName)
{
if (audioType.Equals("mp4", StringComparison.OrdinalIgnoreCase))
{
AdvancedPlayer.PlayMp4(fileName);
}
else if (audioType.Equals("vlc", StringComparison.OrdinalIgnoreCase))
{
AdvancedPlayer.PlayVlc(fileName);
}
}
}
// Client class
public class AudioPlayer : IMediaPlayer
{
private MediaAdapter? mediaAdapter;
public void Play(string audioType, string fileName)
{
// Built-in support for mp3
if (audioType.Equals("mp3", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine($"Playing MP3 file: {fileName}");
}
// Use adapter for other formats
else if (audioType.Equals("mp4", StringComparison.OrdinalIgnoreCase) ||
audioType.Equals("vlc", StringComparison.OrdinalIgnoreCase))
{
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.Play(audioType, fileName);
}
else
{
Console.WriteLine($"Invalid media type: {audioType}");
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== Adapter Pattern Demo ===");
Console.WriteLine();
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.Play("mp3", "song.mp3");
audioPlayer.Play("mp4", "video.mp4");
audioPlayer.Play("vlc", "movie.vlc");
audioPlayer.Play("avi", "video.avi");
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}