Kantor w C#

Jak działa prosty przelicznik walut z loggerem i providerem kursów

1. Opis projektu

Program to prosty kantor walutowy napisany w C# działający w konsoli. Umożliwia przeliczanie kwot między walutami (np. PLN → USD), korzystając z dostarczonego przez program FixedRateProvider.

2. Główne klasy

ILogger i ConsoleLogger

Interfejs do logowania operacji. Klasa ConsoleLogger wypisuje komunikaty w konsoli.

 public class ConsoleLogger : ILogger
{
    public void Info(string message)
    {
        Console.WriteLine($"[INFO] {message}");
    }
    public void Warn(string message)
    {
        Console.WriteLine($"[WARN] {message}");
    }
    public void Error(string message)
    {
        Console.WriteLine($"[ERR ] {message}");
    }

    public void Info1(decimal amount, decimal result, string from, string to)
    {
        Console.WriteLine($"[INFO] Przeliczono {amount} {from.ToUpper()}-> {result} {to.ToUpper()}(pośrednio przez PLN)");
        Console.WriteLine($"{amount} {from} = {result} {to}");
    }
}

IRateProvider i FixedRateProvider

Dostarcza kursy walut.

public interface IRateProvider {
    decimal GetRate(string fromCurrency, string toCurrency);
}

public class FixedRateProvider : IRateProvider {
    public decimal GetRate(string from, string to) {
        if (from == "pln" && to == "usd") return 0.25m;
        if (from == "usd" && to == "pln") return 4.00m;
        return 1.0m;
    }
}

CurrencyConverter

Łączy powyższe komponenty. Używa IRateProvider do przeliczania i ILogger do zapisywania informacji o transakcjach.

public class CurrencyConverter
{
    IRateProvider _rateProvider;
    ILogger _logger;
    public CurrencyConverter(IRateProvider iRateProvider, ILogger iLogger)
    {
        _rateProvider = iRateProvider;
        _logger = iLogger;
    }
    public decimal? Convert(decimal amount, string from, string to)
    {
        var fromCurrency = _rateProvider.GetRate(from);
        if (!fromCurrency.HasValue)
        {
            return null;
        }
        var amountInPLN = amount * fromCurrency;
        var toCurrency = _rateProvider.GetRate(to);
        if (!toCurrency.HasValue) 
        {
            return null;
        }
        var amountInTo = amountInPLN * toCurrency;
        return amountInTo;
    }
}

3. Uruchomienie programu

Użytkownik wpisuje w konsoli polecenia w formacie:

convert 1000 usd pln

Program wypisze wynik konwersji i zaloguje operację.

4. Pobierz projekt

Cały projekt możesz pobrać jako archiwum ZIP i uruchomić w Visual Studio lub Riderze.

Pobierz Kantor