Programmation orientée objet en shell#
Types définis par l'utilisateur.#
Définition#
- Peuvent être défini soit par une bibliothèque partagée,
- soit au moyen de la nouvelle commande de déclaration typeset -T,
- soit au moyen de la commande de déclaration enum.
- Fournissent un moyen de déclarer et d'instancier des objets
- peuvent contenir des données (éléments),
- peuvent contenir des méthodes (fonctions contraintes)
Exemple#
typeset -T Point_t=( ... )
Note: Par convention, les noms de types commencent par une majuscule et se terminent par _t.
Création de types et d'instances#
Une instance d'un type est créée en invoquant le nom du type suivi d'un ou plusieurs noms d'instance.
Point_t point
Lorsqu'un type est défini, une commande intégrée spéciale de ce nom est ajoutée à la liste des commandes intégrées que ksh93 connaît. Les définitions de type sont en lecture seule et ne peuvent pas être annulées.
Using Types To Create Object Orientated Korn Shell 93 Scripts
Exemple#
#!/usr/bin/env ksh93
typeset -T Point_t=(
integer -h 'x coordinate' x=0
integer -h 'y coordinate' y=0
typeset -h 'point color' color="red"
function getcolor {
print -r ${_.color}
}
function setcolor {
_.color=$1
}
setxy() {
_.x=$1; _.y=$2
}
getxy() {
print -r "(${_.x},${_.y})"
}
)
Exemple (suite)#
Point_t point
echo "Initial coordinates are (${point.x},${point.y}). Color is ${point.color}"
point.setxy 5 6
point.setcolor blue
echo "New coordinates are ${point.getxy}. Color is ${point.getcolor}"
Résultat#
$ ./example1
Initial coordinates are (0,0). Color is red
New coordinates are (5,6). Color is blue
Getters#
Définition#
Un getter est une fonction qui est appelée quand un certaine variable est lue.
function demo.get {
.sh.value="3"
echo "Getter called"
}
Exemple#
$ echo $demo
Getter called
3
Setters#
Définition#
Un setter est une fonction qui est appelée quand un certaine variable est modifiée.
function demo.set {
echo "Setter called"
echo "${.sh.value}"
}
Exemple#
$ demo=3
Setter called
3
Documentation auto-générée#
$ Point_t --man
NAME
Point_t - set the type of variables to Point_t
SYNOPSIS
Point_t [ options ] [name[=value]...]
DESCRIPTION
Point_t sets the type on each of the variables specified by name to Point_t. If =value is
specified, the variable name is set to value before the variable is converted to Point_t.
If no names are specified then the names and values of all variables of this type are
written to standard output.
Point_t is built-in to the shell as a declaration command so that field splitting and
pathname expansion are not performed on the arguments. Tilde expansion occurs on
value.
OPTIONS
-r Enables readonly. Once enabled, the value cannot be changed or unset.
-a[type] Indexed array. Each name will converted to an index array of type Point_t. If
a variable already exists, the current value will become index 0. If [type] is
...