He creado un patrón observador que tiene por finalidad simular una estación del clima y dispositivos que se actualizan con la información, la información de la temperatura, presión y viento se generan randómicamente. Dentro del Controlador, he creado un timer que se ejecuta cada 5 segundos llamando al método Notify de la estación, a fin que la información de la estación del clima sea actualizada.
Lo que no logro conseguir es que esa información sea actualizada en la vista, no sé como hacerlo. Qué debo utilizar, si hay algún ejemplo que me pueda ayudar.
Se tiene las siguientes clases:
- IObserverSubject
- IObserverObserver
- IDisplay
- ObserverConcreteObservable
- ObserverConcreteObserver_PhoneDisplay
- ObserverConcreteObserver_WindowDisplay
- Modelo y ViewModel
- ObserverModel
- ObserverModelViewModel
Quedando su diagrama UML de la siguiente forma:
El código fuente de cada clase / interfase es el siguiente:
IDisplay
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
{
public interface IDisplay
{
public ObserverModel Display();
}
}
IObserverSubject
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
{
public interface IObserverSubject
{
public void Add(IObserverObserver ob);
public void Remove(IObserverObserver ob);
public void Notify();
}
}
IObserverObserver
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
{
public interface IObserverObserver
{
public void Update();
}
}
ObserverConcreteObservable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
{
public class ObserverConcreteObservable : IObserverSubject
{
private readonly List<IObserverObserver> observers = new List<IObserverObserver>();
private int param_temp = 0;
private int param_presure = 0;
private int param_wind = 0;
private readonly Random _random = new Random();
public void Add(IObserverObserver observer)
{
observers.Add(observer);
}
public void Notify()
{
foreach(IObserverObserver observer in observers)
{
observer.Update();
}
}
public void Remove(IObserverObserver observer)
{
observers.Remove(observer);
}
public int GetTemperatureState()
{
this.param_temp = _random.Next(-90, 90);
return this.param_temp;
}
public int GetPresureState()
{
this.param_presure = _random.Next(0, 1500);
return this.param_presure;
}
public int GetWindState()
{
this.param_wind = _random.Next(0, 600);
return this.param_wind;
}
}
}
ObserverConcreteObserver_PhoneDisplay
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
{
public class ObserverConcreteObserver_PhoneDisplay : IObserverObserver, IDisplay
{
ObserverConcreteObservable observerSubject;
ObserverModel observerModel = new ObserverModel();
public ObserverConcreteObserver_PhoneDisplay(ObserverConcreteObservable observerSubject)
{
this.observerSubject = observerSubject;
}
public ObserverModel Display()
{
return this.observerModel;
}
public void Update()
{
observerModel.Temperature= this.observerSubject.GetTemperatureState();
observerModel.Presure= this.observerSubject.GetPresureState();
observerModel.Wind =this.observerSubject.GetWindState();
observerModel.Name = "Phone Display";
}
}
}
ObserverConcreteObserver_WindowDisplay
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
{
public class ObserverConcreteObserver_WindowDisplay : IObserverObserver, IDisplay
{
ObserverConcreteObservable observerSubject;
ObserverModel observerModel = new ObserverModel();
public ObserverConcreteObserver_WindowDisplay(ObserverConcreteObservable observerSubject)
{
this.observerSubject = observerSubject;
}
public ObserverModel Display()
{
return this.observerModel;
}
public void Update()
{
observerModel.Temperature = this.observerSubject.GetTemperatureState();
observerModel.Presure = this.observerSubject.GetPresureState();
observerModel.Wind = this.observerSubject.GetWindState();
observerModel.Name = "Window Display";
}
}
}
ObserverModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
{
public class ObserverModel
{
public int Temperature { get; set; }
public int Presure { get; set; }
public int Wind { get; set; }
public string Name { get; set; }
}
}
ObserverModelViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
{
public class ObserverModelViewModel
{
public ObserverModelViewModel()
{
ObserverDisplays = new List<ObserverModel>();
}
public List<ObserverModel> ObserverDisplays { get; set; }
}
}
El controlador: ObserverController
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Areas.DesignPatterns.Models.ObserPattern.ObserverLocation;
using WebApplication1.Areas.DesignPatterns.Models.ObserPattern.ObserverReactive_Extensions;
using WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern;
using WebApplication1.Areas.DesignPatterns.Models.StrategyPattern.Strategy;
using WebApplication1.Areas.DesignPatterns.Models.StrategyPattern.StrategyLog;
using WebApplication1.Areas.DesignPatterns.Models.StrategyPattern.StrategyOperation;
using WebApplication1.Areas.DesignPatterns.Models.StrategyPattern.StrategySort;
using static WebApplication1.Areas.DesignPatterns.Models.ObserPattern.ObserverLocation.ParaLocation;
namespace WebApplication1.Areas.DesignPatterns.Controllers
{
public class ObserverController : Controller
{
public IActionResult ObserPattern()
{
ObserverConcreteObservable weatherStation = new ObserverConcreteObservable();
ObserverConcreteObserver_PhoneDisplay phoneDisplay = new ObserverConcreteObserver_PhoneDisplay(weatherStation);
ObserverConcreteObserver_WindowDisplay windowDisplay = new ObserverConcreteObserver_WindowDisplay(weatherStation);
weatherStation.Add(phoneDisplay);
weatherStation.Add(windowDisplay);
var timer = new System.Timers.Timer(TimeSpan.FromSeconds(5).TotalMilliseconds); // se ejecutara cada x segundos
timer.Elapsed += async (sender, e) => {
weatherStation.Notify();
};
timer.Start(); // indicamos que unicie
//Console.ReadKey();
ObserverModelViewModel observerModelViewModel = new ObserverModelViewModel();
observerModelViewModel.ObserverDisplays.Add(phoneDisplay.Display());
observerModelViewModel.ObserverDisplays.Add(windowDisplay.Display());
return View(observerModelViewModel);
}
}
}
La vista: ObserPattern
@using WebApplication1.Areas.DesignPatterns.Models.Observer.ObserPattern
@model ObserverModelViewModel
@{
ViewData["Title"] = "ObserPattern";
}
<h1>ObserPattern</h1>
@foreach (var element in Model.ObserverDisplays)
{
<h2> @element.Name</h2>
<h2>Temperature: @element.Temperature</h2>
<h2>Presure: @element.Presure</h2>
<h2>Wind: @element.Wind</h2>
<br />
}
<div>
<a class="btn btn-primary" href="@Url.Action("Index","Home", new { area = "" })">Retornar1</a>
</div>