Ответы к экзамену 0.4, страница 2
Описание файла
PDF-файл из архива "Ответы к экзамену 0.4", который расположен в категории "". Всё это находится в предмете "распределённые ис и базы данных" из 9 семестр (1 семестр магистратуры), которые можно найти в файловом архиве НИУ «МЭИ» . Не смотря на прямую связь этого архива с НИУ «МЭИ» , его также можно найти и в других разделах. Архив можно найти в разделе "к экзамену/зачёту", в предмете "распределённые ис и базы данных" в общих файлах.
Просмотр PDF-файла онлайн
Текст 2 страницы из PDF
Реальное количество может быть меньше/// этого значения, поскольку возвращаемая/// величина - это количество "мягких" ссылок в пуле.public Int32 Size{get{lock (pool){return pool.Count;}}}public Int32 InstanceCount { get { return instanceCount; } }public Int32 MaxInstances{get { return maxInstances; }set { maxInstances = value; }}public T GetObject(){lock (pool){T thisObject = RemoveObject();if (thisObject != null)return thisObject;if (InstanceCount < MaxInstances)return CreateObject();return null;}}public T WaitForObject(){lock (pool){T thisObject = RemoveObject();if (thisObject != null)return thisObject;if (InstanceCount < MaxInstances)return CreateObject();}semaphore.WaitOne();return WaitForObject();}/// Удаляет объект из коллекции пула и возвращает егоprivate T RemoveObject(){while (pool.Count > 0){var refThis = (WeakReference)pool[pool.Count - 1];pool.RemoveAt(pool.Count - 1);var thisObject = (T)refThis.Target;if (thisObject != null)return thisObject;instanceCount--;}return null;}private T CreateObject(){T newObject = creator.Create();instanceCount++;return newObject;}/// Освобождает объект, помещая его в пул для повторного использованияpublic void Release(T obj){if (obj == null)throw new NullReferenceException();lock (pool){var refThis = new WeakReference(obj);pool.Add(refThis);semaphore.Release();}}}public class Reusable{public Object[] Objs { get; protected set; }public Reusable(params Object[] objs){Objs = objs;}}public class Creator : ICreation<Reusable>{private static Int32 _id;public Reusable Create(){++_id;return new Reusable(_id);}}public class ReusablePool : ObjectPool<Reusable>{public ReusablePool() : base(new Creator(), 2) { }}class Program{static void Main(){Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);var reusablePool = new ReusablePool();var thrd1 = new Thread(Run);var thrd2 = new Thread(Run);var thisObject1 = reusablePool.GetObject();var thisObject2 = reusablePool.GetObject();thrd1.Start(reusablePool);thrd2.Start(reusablePool);ViewObject(thisObject1);ViewObject(thisObject2);Thread.Sleep(2000);reusablePool.Release(thisObject1);Thread.Sleep(2000);reusablePool.Release(thisObject2);Console.ReadKey();}private static void Run(Object obj){Console.WriteLine("\t" + System.Reflection.MethodBase.GetCurrentMethod().Name);var reusablePool = (ReusablePool)obj;Console.WriteLine("\tstart wait");var thisObject1 = reusablePool.WaitForObject();ViewObject(thisObject1);Console.WriteLine("\tend wait");reusablePool.Release(thisObject1);}private static void ViewObject(Reusable thisObject){foreach (var obj in thisObject.Objs){Console.Write(obj + @" ");}Console.WriteLine();}}using System;abstract class Prototype{private string id;public string Id{get { return id; }}public Prototype(string id){this.id = id;}public abstract Prototype Clone();}class ConcretePrototype1 : Prototype{public ConcretePrototype1(string id) : base(id) { }public override Prototype Clone(){return (Prototype) this.MemberwiseClone();}}class ConcretePrototype2 : Prototype{public ConcretePrototype2(string id) : base(id) { }public override Prototype Clone(){return (Prototype) this.MemberwiseClone();}}class Program{static void Main(string[] args){Prototype p1 = new ConcretePrototype1("I");Prototype c1 = p1.Clone();Console.WriteLine("Cloned: {0}", c1.Id);Prototype p2 = new ConcretePrototype2("II");Prototype c2 = p2.Clone();Console.WriteLine("Cloned: {0}", c2.Id);Console.ReadKey();}}#include <cstdio>#include <stdexcept>class file{public:file( const char* filename ) : m_file_handle(std::fopen(filename, "w+")){if( !m_file_handle )throw std::runtime_error("file open failure") ;}~file(){if(std::fclose(m_file_handle) != 0){// fclose() может вернуть ошибку при записи на диск последних изменений}}void write(const char* str){if(std::fputs(str, m_file_handle) == EOF)throw std::runtime_error("file write failure");}private:std::FILE* m_file_handle;// Копирование и присваивание не реализовано.// объявив соответствующие методы закрытыми.file( const file &);file & operator = (const file & ) ;Предотвратим их использование,};int _tmain(int argc, _TCHAR* argv[]){// открываем файл (захватываем ресурс)file logfile("logfile.txt") ;logfile.write("hello logfile!") ;// продолжаем использовать logfile...// Можно возбуждать исключения или выходить из функции не беспокоясь о закрытии файла;// он будет закрыт автоматически когда переменная logfile выйдет из области видимости.return 0;}using System;class Singleton{static Singleton instance;private Singleton() { }public static Singleton Instance{get{if (instance == null){instance = new Singleton();}return instance;}}public int Property{get;set;}}class Program{static void Main(string[] args){Singleton instance = Singleton.Instance;instance.Property = 3;Console.WriteLine("Значение свойства: " + instance.Property);instance.Property = 2;Console.WriteLine("Значение свойства: " + instance.Property);Console.ReadKey();}}class Multiton{static Dictionary<object, Multiton> instances = new Dictionary<object, Multiton>();Multiton() { }public static Multiton Instance(object key){Multiton instance;if (!instances.TryGetValue(key, out instance)){instance = new Multiton();instances.Add(key, instance);}return instance;}public int Property { get; set; }}class Program{static void Main(string[] args){Console.WriteLine("Новый объект");Multiton instance1 = Multiton.Instance("Ключ 1");instance1.Property = 3;Console.WriteLine("Значение свойства: " + instance1.Property);instance1.Property = 2;Console.WriteLine("Значение свойства: " + instance1.Property);Multiton instance2 = Multiton.Instance(123);instance2.Property = 11;Console.WriteLine("Новый объект");Console.WriteLine("Значение свойства: " + instance2.Property);Console.Read();}}abstract class Worker{protected Worker successor;public void SetSuccessor(Worker successor){this.successor = successor;}public abstract void Execute(int difficulty);}class Novice : Worker{public override void Execute(int difficulty){if (difficulty < 1){Console.WriteLine(this.GetType().Name, difficulty);}else if (successor != null){successor.Execute(difficulty);}}}class Specialist : Worker{public override void Execute(int difficulty){if (difficulty < 2){Console.WriteLine(this.GetType().Name, difficulty);}else if (successor != null){successor.Execute(difficulty);}}}class Expert : Worker{public override void Execute(int difficulty){if (difficulty < 3){Console.WriteLine(this.GetType().Name, difficulty);}else if (successor != null){successor.Execute(difficulty);}}}class Program{static void Main(string[] args){Worker novice = new Novice();Worker specialist = new Specialist();Worker expert = new Expert();novice.SetSuccessor(specialist);specialist.SetSuccessor(expert);novice.Execute(1);Console.Read();}}interface Command{void Execute();}class Command1 : Command{Reciever reciever;public Command1(Reciever reciever){this.reciever = reciever;}public void Execute(){reciever.setOn();}}class Command2 : Command{Reciever reciever;public Command2(Reciever reciever){this.reciever = reciever;}public void Execute(){reciever.setOff();}}class Invoker{private Command command;public void setCommand(Command command){this.command = command;}public void invokeCommand(){command.Execute();}}class Reciever{bool field;public void showField(){Console.WriteLine(field);}public void setOn(){field = true;}public void setOff(){field = false;}}class Program{static void Main(string[] args){Invoker invoker = new Invoker();Reciever reciever = new Reciever();Command1 c1 = new Command1(reciever);Command2 c2 = new Command2(reciever);invoker.setCommand(c1);invoker.invokeCommand();reciever.showField();invoker.setCommand(c2);invoker.invokeCommand();reciever.showField();Console.Read();}}abstract class Expression{public void Interpret(Context context){if (context.Input.Length == 0)return;if (context.Input.StartsWith(Nine())){context.Output += (9 * Multiplier());context.Input = context.Input.Substring(2);}else if (context.Input.StartsWith(Four())){context.Output += (4 * Multiplier());context.Input = context.Input.Substring(2);}else if (context.Input.StartsWith(Five())){context.Output += (5 * Multiplier());context.Input = context.Input.Substring(1);}while (context.Input.StartsWith(One())){context.Output += (1 * Multiplier());context.Input = context.Input.Substring(1);}}public abstract string One();public abstract string Four();public abstract string Five();public abstract string Nine();public abstract int Multiplier();}class ThousandExpression : Expression{public override string One() { return "M"; }public override string Four() { return " "; }public override string Five() { return " "; }public override string Nine() { return " "; }public override int Multiplier() { return 1000; }}class HundredExpression : Expression{public override string One() { return "C"; }public override string Four() { return "CD"; }public override string Five() { return "D"; }public override string Nine() { return "CM"; }public override int Multiplier() { return 100; }}class TenExpression{public overridepublic overridepublic overridepublic overridepublic override}: Expressionclass OneExpression{public overridepublic overridepublic overridepublic overridepublic override}: Expressionstring One() { return "X"; }string Four() { return "XL"; }string Five() { return "L"; }string Nine() { return "XC"; }int Multiplier() { return 10; }string One() { return "I"; }string Four() { return "IV"; }string Five() { return "V"; }string Nine() { return "IX"; }int Multiplier() { return 1; }class OneExpression{static void Main(string[] args){string roman = "MCMXXVIII";Context context = new Context(roman);List<Expression> tree = new List<Expression>();tree.Add(newtree.Add(newtree.Add(newtree.Add(newThousandExpression());HundredExpression());TenExpression());OneExpression());foreach (Expression exp in tree)exp.Interpret(context);Console.WriteLine("{0} = {1}", roman, context.Output);Console.ReadKey();}}usingusingusingusingSystem;System.Collections.Generic;System.Linq;System.Text;namespace MediatorPattern{class Colleague{bool isON;public bool IsON{get { return isON; }set {mediator.Send(this, value);this.isON = value;}}string info;public string Info{get { return info; }set { info = value; }}Mediator mediator;public Colleague(Mediator med) {this.mediator = med;this.isON = true;}}class Mediator{Colleague colleague1, colleague2;internal Colleague Colleague2{get { return colleague2; }set { colleague2 = value; }}internal Colleague Colleague1{get { return colleague1; }set { colleague1 = value; }}public void Send(Colleague colleague, bool value){Colleague col = colleague == colleague1 ? colleague2 : colleague1;if (value){col.Info = "My colleague doesn't sleep!";}else{col.Info = "My colleague is asleep";}}}class Program{static void Main(string[] args){Mediator mediator = new Mediator();Colleague col1 = new Colleague(mediator);Colleague col2 = new Colleague(mediator);mediator.Colleague1 = col1;mediator.Colleague2 = col2;col1.IsON = true;col2.IsON = false;Console.WriteLine(col1.Info);Console.WriteLine(col2.Info);col1.IsON = false;col2.IsON = true;Console.WriteLine(col1.Info);Console.WriteLine(col2.Info);Console.ReadLine();}}}usingusingusingusingSystem;System.Collections.Generic;System.Linq;System.Text;namespace Memento{public interface IBankAccount{object getSavePoint();void setSavePoint(object point);}public class BankAccount : IBankAccount{public int numbLastTrans { get; set; }public int balance { get; set; }public BankAccount(int NumbLastTrans = 0, int Balance = 0){this.balance = Balance;this.numbLastTrans = NumbLastTrans;}public void Print(){Console.WriteLine("=======================");Console.WriteLine("Последняя успешно завершенная транзакция: {0}", this.numbLastTrans);Console.WriteLine("Ваш баланс: {0}", this.balance);Console.WriteLine("=======================");}object IBankAccount.getSavePoint(){return new SavePoint { numbLastTrans = this.numbLastTrans, balance = this.balance };}void IBankAccount.setSavePoint(object savepoint){if (Object.ReferenceEquals(savepoint, null))throw new ArgumentNullException("savepoint is null");if (!(savepoint is SavePoint))throw new ArgumentException("savepoint is not SavePoint");numbLastTrans = ((SavePoint)savepoint).numbLastTrans;balance = ((SavePoint)savepoint).balance;}}class SavePoint{public int numbLastTrans { get; set; }public int balance { get; set; }}public class Saver{private object savepoint;public void SaveState(IBankAccount bankaccount){if (bankaccount == null)throw new ArgumentNullException("bankaccount");savepoint = bankaccount.getSavePoint();}public void RestoreState(IBankAccount bankaccount){if (bankaccount == null)throw new ArgumentNullException("bankaccount");if (savepoint == null)throw new InvalidOperationException("bankaccount == null");bankaccount.setSavePoint(savepoint);}}class Program{static void Main(string[] args){Console.WriteLine("Создан банковский счет");BankAccount myAccount = new BankAccount();Saver saver = new Saver();saver.SaveState(myAccount);myAccount.Print();Console.ReadKey();Random rand = new Random();int sum = 0, p = 0;for (int i = 1; i <= 5; i++){sum = rand.Next(10000) - 5000;myAccount.numbLastTrans = i;myAccount.balance += sum;Console.WriteLine("Готовится к выполнению банковская операция");Console.WriteLine("Номер операции : {0}, сумма : {1} руб.", i, sum);Console.ReadKey();p = rand.Next(10);if (p % 2 == 0){Console.ForegroundColor = ConsoleColor.Green;Console.WriteLine("Финансовая операция проведена успешно");Console.ResetColor();saver.SaveState(myAccount);}else{Console.ForegroundColor = ConsoleColor.Red;Console.WriteLine("При выполнении финансовой операции произошел сбой");Console.ResetColor();saver.RestoreState(myAccount);Console.WriteLine("Баланс после восстановления:");}myAccount.Print();Console.ReadKey();}}}}public class ConsoleTipsWriter : ITipsObserver{public ConsoleTipsWriter(TipsPublisher aPublisher){mPublisher = aPublisher;}public void onNewTip(){Console.WriteLine("NEW TIP IS " + mPublisher.getTipOfTheDay());}TipsPublisher mPublisher;}public interface ITipsObserver{void onNewTip();}public class TipsBeeper : ITipsObserver{public void onNewTip(){Console.Beep();}}public class TipsPublisher{public TipsPublisher(){mTipOfTheDay = "DEFAULT TIP";}public void subscribe(ITipsObserver aObserver){mObservers.Add(aObserver);}public void unsubscribe(ITipsObserver aObserver){mObservers.Remove(aObserver);}public String getTipOfTheDay(){return mTipOfTheDay;}public void setTipOfTheDay(String aTipOfTheDay){mTipOfTheDay = aTipOfTheDay;notify();}public void notify(){foreach (ITipsObserver observer in mObservers){observer.onNewTip();}}String mTipOfTheDay;List<ITipsObserver> mObservers = new List<ITipsObserver>();}class Program{static void Main(string[] args){testObserver();Console.ReadLine();}static void testObserver(){Console.Out.WriteLine(">>>>TEST OBSERVER<<<<<");TipsPublisher publisher = new TipsPublisher();ConsoleTipsWriter writer = new ConsoleTipsWriter(publisher);publisher.subscribe(writer);publisher.setTipOfTheDay("DONT WORRY!");System.Threading.Thread.Sleep(2000);TipsBeeper beeper = new TipsBeeper();publisher.subscribe(beeper);publisher.setTipOfTheDay("BE HAPPY!");System.Threading.Thread.Sleep(2000);publisher.unsubscribe(writer);publisher.setTipOfTheDay("BE HUGGIES!");}}using System;namespace StatePattern{class DKA{private IState state;private IState stateS;private IState stateQ;private IState stateF;public DKA(){stateS = new S();stateQ = new Q();stateF = new F();state = stateS;}public bool check(string s){state = stateS;char[] symbols = s.ToCharArray();foreach(char symbol in symbols) {if (!Transition(Int32.Parse(symbol.ToString())))return false;}bool result = state.Finish();state = stateS;return result;}public bool Transition(int s){if (state is F) {if (s >= 1 && s <= 9) {state = stateQ;return true;}return (s == 0);}if (state is Q) {if (s == 0) {state = stateF;return true;}return false;}else // state is S{if (s >= 1 && s <= 9) {state = stateQ;return true;}return (s == 0);}}}interface IState{bool Finish();}abstract class State { }class S : State, IState{public bool Finish(){return false;}}class Q : State, IState{public bool Finish(){return false;}}class F : State, IState{public bool Finish(){return true;}}}public sealed class Singleton{private Singleton(){// инициализировать новый экземпляр объекта}private static volatile Singleton singletonInstance;private static readonly Object syncRoot = new Object();public static Singleton GetInstance(){// создан ли объектif (singletonInstance == null){// нет, не создан// только один поток может создать егоlock (syncRoot){// проверяем, не создал ли объект другой потокif (singletonInstance == null){// нет не создал — создаёмsingletonInstance = new Singleton();}}}return singletonInstance;}}usingusingusingusingusingSystem;System.Data;System.Drawing;System.Windows.Forms;System.Threading;namespace LeaderFollower{class Leader{static public int[][] matrixMultiplication(int[][] A, int[][] B){Follower[][] followers = new Follower[A.Length][];Thread[][] threads = new Thread[A.Length][];for (int i = 0; i < A.Length; i++){threads[i] = new Thread[A.Length];followers[i] = new Follower[A.Length];for (int j = 0; j < A.Length; j++){followers[i][j] = new Follower(A[i], B[j]);threads[i][j] = new Thread(new ThreadStart(followers[i][j].count));threads[i][j].Start();}}for (int i = 0; i < A.Length; i++)for (int j = 0; j < A.Length; j++)threads[i][j].Join();int[][] result = new int[A.Length][];for (int i = 0; i < A.Length; i++){result[i] = new int[A.Length];for (int j = 0; j < A.Length; j++)result[i][j] = followers[i][j].result;}return result;}}class Follower{public int result = 0;private int[] A;private int[] B;public Follower(int[] A, int[] B){this.A = A; this.B = B;}public void count(){for (int i = 0; i < A.Length; i++)result += A[i] * B[i];}}public partial class Form1 : Form{private System.Windows.Forms.TextBox[][] A = new System.Windows.Forms.TextBox[3][];private System.Windows.Forms.TextBox[][] B = new System.Windows.Forms.TextBox[3][];private System.Windows.Forms.TextBox[][] C = new System.Windows.Forms.TextBox[3][];private int[][] Amatrix = new int[3][];private int[][] Bmatrix = new int[3][];private int[][] Cmatrix = new int[3][];public Form1() {InitializeComponent();System.Drawing.Font font = new System.Drawing.Font("Microsoft Sans Serif", 12F,System.Drawing.FontStyle.Regular,System.Drawing.GraphicsUnit.Point,((byte)(204)));HorizontalAlignment center = System.Windows.Forms.HorizontalAlignment.Center;System.Random rand = new System.Random();for (int i = 0; i < 3; i++) {A[i] = new System.Windows.Forms.TextBox[4];Amatrix[i] = new int[4];for (int j = 0; j < 4; j++) {Amatrix[i][j] = rand.Next(0, 10);A[i][j] = new System.Windows.Forms.TextBox();A[i][j].Font = font;A[i][j].Location = new System.Drawing.Point(40 + 54 * j, 45 + 30 * i);A[i][j].Size = new System.Drawing.Size(50, 26);A[i][j].Text = Amatrix[i][j].ToString();A[i][j].TextAlign = center;this.Controls.Add(A[i][j]);}}for (int i = 0; i < 3; i++) {B[i] = new System.Windows.Forms.TextBox[4];Bmatrix[i] = new int[4];for (int j = 0; j < 4; j++) {Bmatrix[i][j] = rand.Next(0, 10);B[i][j] = new System.Windows.Forms.TextBox();B[i][j].Font = font;B[i][j].Location = new System.Drawing.Point(300 + 54 * i, 30 + 30 * j);B[i][j].Size = new System.Drawing.Size(50, 26);B[i][j].Text = Bmatrix[i][j].ToString();B[i][j].TextAlign = center;this.Controls.Add(B[i][j]);}}Cmatrix = Leader.matrixMultiplication(Amatrix, Bmatrix);for (int i = 0; i < 3; i++) {C[i] = new System.Windows.Forms.TextBox[3];for (int j = 0; j < 3; j++) {C[i][j] = new System.Windows.Forms.TextBox();C[i][j].Font = font;C[i][j].Location = new System.Drawing.Point(510 + 54 * j, 45 + 30 * i);C[i][j].Size = new System.Drawing.Size(50, 26);C[i][j].Text = Cmatrix[i][j].ToString();C[i][j].TextAlign = center;this.Controls.Add(C[i][j]);}}}}}using System;using System.Threading;using System.Collections;class MonitorSample{const int MAX_LOOP_TIME = 1000;Queue m_smplQueue;public MonitorSample(){m_smplQueue = new Queue();}public void FirstThread(){int counter = 0;lock (m_smplQueue){while (counter < MAX_LOOP_TIME){//Wait, if the queue is busy.Monitor.Wait(m_smplQueue);//Push one element.m_smplQueue.Enqueue(counter);//Release the waiting thread.Monitor.Pulse(m_smplQueue);counter++;}}}public void SecondThread(){lock (m_smplQueue){//Release the waiting thread.Monitor.Pulse(m_smplQueue);//Wait in the loop, while the queue is busy.//Exit on the time-out when the first thread stops.while (Monitor.Wait(m_smplQueue, 1000)){//Pop the first element.int counter = (int)m_smplQueue.Dequeue();//Print the first element.Console.WriteLine(counter.ToString());//Release the waiting thread.Monitor.Pulse(m_smplQueue);}}}//Return the number of queue elements.public int GetQueueCount(){return m_smplQueue.Count;}static void Main(string[] args){//Create the MonitorSample object.MonitorSample test = new MonitorSample();//Create the first thread.Thread tFirst = new Thread(new ThreadStart(test.FirstThread));//Create the second thread.Thread tSecond = new Thread(new ThreadStart(test.SecondThread));//Start threads.tFirst.Start();tSecond.Start();//wait to the end of the two threadstFirst.Join();tSecond.Join();//Print the number of queue elements.Console.WriteLine("Queue Count = " + test.GetQueueCount().ToString());}}usingusingusingusingusingusingusingSystem;System.Collections.Generic;System.Text;System.Threading;System.Net;System.Net.Sockets;System.Linq;public interface ISynchronousEventDemultiplexer{IList<TcpListener> Select(ICollection<TcpListener> listeners);}public class SynchronousEventDemultiplexer : ISynchronousEventDemultiplexer{public IList<TcpListener> Select(ICollection<TcpListener> listeners){var tcpListeners =new List<TcpListener>(from listener in listenerswhere listener.Pending()select listener);return tcpListeners;}}public interface IEventHandler{void HandleEvent(byte[] data);TcpListener GetHandler();}public class MessageEventHandler : IEventHandler{private readonly TcpListener _listener;public MessageEventHandler(IPAddress ipAddress, int port){_listener = new TcpListener(ipAddress, port);}public void HandleEvent(byte[] data){string message = Encoding.UTF8.GetString(data);}public TcpListener GetHandler(){return _listener;}}public interface IReactor{void RegisterHandle(IEventHandler eventHandler);void RemoveHandle(IEventHandler eventHandler);void HandleEvents();}public class Reactor : IReactor{ISynchronousEventDemultiplexer _synchronousEventDemultiplexer;IDictionary<TcpListener, IEventHandler> _handlers;public Reactor(ISynchronousEventDemultiplexer synchronousEventDemultiplexer){_synchronousEventDemultiplexer = synchronousEventDemultiplexer;_handlers = new Dictionary<TcpListener, IEventHandler>();}public void RegisterHandle(IEventHandler eventHandler){_handlers.Add(eventHandler.GetHandler(), eventHandler);}public void RemoveHandle(IEventHandler eventHandler){_handlers.Remove(eventHandler.GetHandler());}public void HandleEvents(){while (true){IList<TcpListener> listeners = _synchronousEventDemultiplexer.Select(_handlers.Keys);foreach (TcpListener listener in listeners){int dataReceived = 0;byte[] buffer = new byte[1];IList<byte> data = new List<byte>();Socket socket = listener.AcceptSocket();do{dataReceived = socket.Receive(buffer);if (dataReceived > 0){data.Add(buffer[0]);}} while (dataReceived > 0);socket.Close();_handlers[listener].HandleEvent(data.ToArray());}}}}class Program{static void Main(string[]{IEventHandler client1IEventHandler client2IEventHandler client3args)= new MessageEventHandler(IPAddress.Parse("123.123.123.123"), 123);= new MessageEventHandler(IPAddress.Parse("234.234.234.234"), 123);= new MessageEventHandler(IPAddress.Parse("125.125.125.125"), 123);ISynchronousEventDemultiplexer synchronousEventDemultiplexer = new SynchronousEventDemultiplexer();Reactor dispatcher = new Reactor(synchronousEventDemultiplexer);dispatcher.RegisterHandle(client1);dispatcher.RegisterHandle(client2);dispatcher.RegisterHandle(client3);dispatcher.HandleEvents();Console.ReadKey();}}Шаблон реализуется следующим образом:usingusingusingusingSystem;System.Collections.Generic;System.Text;System.Threading;/// <summary>/// Экземпляры классов в этой роли управляют обработкой объектов Request <see cref="JournalEntry"/>,/// выполняемой объектом Processor <see cref="Printer"/>.