Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Задание 1

Задание: Напишите класс Timer, который имеет событие типа EventHandler с именем Tick, которое возникает каждую секунду. Затем напишите класс Clock, который подписывается на это событие и выводит на консоль текущее время при каждом его возникновении. Затем напишите класс Counter, который также подписывается на это событие и увеличивает свое значение на единицу при каждом его возникновении. Продемонстрируйте работу этих классов в методе Main

Результат:

<img width="269" height="248" alt="изображение" src="https://github.com/user-attachments/assets/bac1f168-ddb4-4b13-98f3-ac7d2d7d055c" />
60 changes: 26 additions & 34 deletions kt8888/Program.cs
Original file line number Diff line number Diff line change
@@ -1,62 +1,54 @@
using System;
using System.IO;

namespace kt8888
{
public class BankAccount
public class Timer
{
private decimal balance;
private System.Timers.Timer _timer;

public decimal Balance
{
get { return balance; }
private set
{
balance = value;
BalanceChanged?.Invoke(balance);
}
}
public event EventHandler Tick;

public event Action<decimal> BalanceChanged;

public void Deposit(decimal amount)
public Timer()
{
Balance += amount;
_timer = new System.Timers.Timer(1000);
_timer.Elapsed += (s, e) => Tick?.Invoke(this, EventArgs.Empty);
}

public void Withdraw(decimal amount)
public void Start() => _timer.Start();
public void Stop() => _timer.Stop();
}

public class Clock
{
public Clock(Timer timer)
{
if (amount <= Balance)
{
Balance -= amount;
}
timer.Tick += (s, e) => Console.WriteLine($"time: {DateTime.Now:T}");
}
}

public class Logger
public class Counter
{
public Logger(BankAccount account)
private int _count = 0;

public Counter(Timer timer)
{
account.BalanceChanged += (balance) =>
{
File.AppendAllText("log.txt", $"balance {balance}\n");
};
timer.Tick += (s, e) => Console.WriteLine($"count: {++_count}");
}
}

class Program
{
static void Main()
{
BankAccount account1 = new BankAccount();
Logger logger1 = new Logger(account1);

account1.Deposit(1000);
account1.Withdraw(500);
account1.Deposit(300);
Timer timer1 = new Timer();
Clock clock1 = new Clock(timer1);
Counter counter1 = new Counter(timer1);

Console.WriteLine("final balance " + account1.Balance);
timer1.Start();
Console.WriteLine("timer started press key for stop");
Console.ReadLine();
timer1.Stop();
Console.WriteLine("timer stopped");
}
}
}