This document describes the basics of the creation of events with a builder. In some cases, each event must have a unique identifier. But because static fields are not allowed in the event definitions, it is impossible to store the next available event ID in a static field. The best way for creating events with unique identifiers is to apply the builder design pattern.
The elements that are explained in this document are:
The purpose of this document is to create an event, which has a unique identifier. This identifier is an integer number that should be incremented each time an event instance is created.
The definition of the event should define the event with a read-only identifier (val
).
Because the identifier is a value, it must be initialize in the constructor of the event.
Consequently, a constructor is defined with the identifier value as parameter.
event MyEvent {
val id : long
new (id : long) {
this.id = id
}
}
For creating the event instances, we apply the builder design pattern
A builder is a class that is able to create an instance of the event when it is invoked.
The next available unique identifier for the events is stored into a field of the builder (id
).
class MyEventBuilder {
private var id : long = 0
def newInstance : MyEvent {
val eventId = id
id++
return new MyEvent(eventId)
}
}
The function newInstance
is defined for creating an instance of the event. This function
gets the next available global identifier to give it to the event instance, and it increments
the next available global identifier for the next call to newInstance
.
Finally, the newInstance
function create the event instance with the appropriate identifier.
For using the event builder, you have simply to create an instance of the MyEventBuilderUser
class, and use it as follow (two events are created in the example):
val builder = new MyEventBuilder
var event1 = builder.newInstance
var event2 = builder.newInstance
Copyright © 2014-2024 SARL.io, the Original Authors and Main Authors.
Documentation text and medias are licensed under the Creative Common CC-BY-SA-4.0; you may not use this file except in compliance with CC-BY-SA-4.0. You may obtain a copy of CC-BY-4.0.
Examples of SARL code are licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the Apache License. You may obtain a copy of the Apache License.
You are free to reproduce the content of this page on copyleft websites such as Wikipedia.
Generated with the translator docs.generator 0.14.0.