Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 4 An Architecture to Suit You

Model View Update (MVU)

Model View Update is a software design pattern for building interactive applications. The concept originates from the Elm programming language. As the name suggests, there are three key parts to MVU:

•\ Model: This is the state of your application.

•\ View: This is a visual representation of your state.

•\ Update: This is a mechanism to update your state.

Figure 4-3 shows how each of these components relate and interact with each other.

Figure 4-3.  An overview of the MVU pattern

This pattern offers several benefits:

•\

Clearly defined rules around where state is allowed to

 

be updated

•\

Ease of testing

A key part to any design pattern is knowing where to locate parts of your code to make it fit and abide by the rules. Let’s take a deeper look at each of the three key parts of this pattern.

83

Chapter 4 An Architecture to Suit You

Getting Started with Comet

First, you must install the Comet project templates. To do this, open a terminal window and run the following command:

dotnet new –install Clancey.Comet.Templates.Multiplatform

This will install the template so that you can create a new project. Sadly, this is different enough to the WidgetBoard project that you have been working with so far.

Next, you need to create the project. This is again done via the terminal for now:

dotnet new comet -–name WidgetBoard.Mvu

This will create a new project that you can start modifying.

Adding Your MVU Implementation

Go ahead and open the project you just created.

The first thing you need to do is make use of the same Scheduler class that you created in the MVVM Model example for your MVU implementation. Here it is again to make life easier:

public class Scheduler

{

public void ScheduleAction(TimeSpan timeSpan, Action action)

{

Task.Run(async () =>

{

await Task.Delay(timeSpan); action.Invoke();

}

84

Chapter 4 An Architecture to Suit You

}

}

Finally, go ahead and create your ClockWidget class:

public class ClockWidget : View

{

[State]

readonly Clock clock = new();

[Body] View body()

=> new Text(() => $"{clock.Time}")

.FontSize(80)

.HorizontalLayoutAlignment(LayoutAlignment.Center)

.VerticalLayoutAlignment(LayoutAlignment.Center);

public class Clock : BindingObject

{

readonly Scheduler scheduler = new();

public DateTime Time

{

get => GetProperty<DateTime>(); set => SetProperty(value);

}

public Clock()

{

SetTime(DateTime.Now);

}

void SetTime(DateTime dateTime)

{

Time = dateTime;

85