Dependency Inversion Principle

This commit is contained in:
Geir Okkenhaug Jerstad 2025-01-06 14:04:39 +01:00
parent e71dc82f85
commit 8dfac53540
5 changed files with 85 additions and 0 deletions

View file

@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DependencyInversionPrinciple", "DependencyInversionPrinciple\DependencyInversionPrinciple.csproj", "{D42BF79A-EB9A-4B1E-A7A8-E0C83D3CD844}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D42BF79A-EB9A-4B1E-A7A8-E0C83D3CD844}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D42BF79A-EB9A-4B1E-A7A8-E0C83D3CD844}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D42BF79A-EB9A-4B1E-A7A8-E0C83D3CD844}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D42BF79A-EB9A-4B1E-A7A8-E0C83D3CD844}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,24 @@
namespace DependencyInversionPrinciple;
public class ChatClient
{
private readonly string _name;
private readonly ChatServer _server;
public ChatClient(string name, ChatServer server)
{
_name = name;
_server = server;
_server.Register(this);
}
public void Say(string message)
{
_server.Broadcast(this, $"{_name} sier: {message}");
}
public void Receive(string message)
{
Console.WriteLine($"{_name} mottok: {message}");
}
}

View file

@ -0,0 +1,28 @@
namespace DependencyInversionPrinciple;
public class ChatServer
{
private readonly List<ChatClient> _clients;
public ChatServer()
{
_clients = new List<ChatClient>();
}
public void Broadcast(ChatClient client, string message)
{
foreach (var chatClient in _clients)
{
if (chatClient != client)
{
chatClient.Receive(message);
}
}
}
public void Register(ChatClient client)
{
_clients.Add(client);
}
}

View file

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,7 @@
using DependencyInversionPrinciple;
var server = new ChatServer();
var client1 = new ChatClient("Per", server);
client1.Say("Hello");