Cours JavaScript et TypeScript · Module 7: TypeScript avancé
Propriétés statiques et abstraites
Dans cette leçon4
« À Jurassic Park, nous avons des protocoles et des standards qui s'appliquent à tous les objets d'une même classe », explique le Dr Henry Wu, généticien en chef du parc. « Par exemple, tous nos enclos de dinosaures suivent la même procédure de sécurité, peu importe l'enclos précis dont on parle. En revanche, chaque espèce de dinosaure possède son propre patron d'ADN unique, mais nous savons tous que l'ADN doit exister - même si les détails diffèrent d'une espèce à l'autre. »
En programmation orientée objet, TypeScript propose deux concepts puissants qui reflètent ces idées :
- Les propriétés et méthodes statiques - partagées par toutes les instances d'une classe
- Les propriétés et méthodes abstraites - qui doivent être implémentées par les classes qui en héritent
Dans cet exercice, nous allons explorer en profondeur ces concepts en créant un système avancé de gestion de la génétique et des protocoles de sécurité pour Jurassic Park.
Propriétés et méthodes statiques
Les éléments statiques d'une classe appartiennent à la classe elle-même, et non à ses instances. Cela signifie que :
- Il n'existe qu'une seule copie de chaque propriété statique, quel que soit le nombre d'instances créées
- L'accès aux propriétés statiques se fait via le nom de la classe, et non via une instance
- Les méthodes statiques peuvent être appelées directement sur la classe
Utilisation de base des éléments statiques
Voyons comment les éléments statiques peuvent être utilisés dans le contexte de Jurassic Park :
class SecurityProtocol {
// Static property - shared by all instances
static readonly LEVEL_CRITICAL: number = 5;
static readonly LEVEL_HIGH: number = 4;
static readonly LEVEL_MEDIUM: number = 3;
static readonly LEVEL_LOW: number = 2;
static readonly LEVEL_MINIMAL: number = 1;
// Static property storing the current global park threat level
private static _currentThreatLevel: number = SecurityProtocol.LEVEL_LOW;
// Instance properties
private readonly area: string;
private localThreatLevel: number;
constructor(area: string) {
this.area = area;
this.localThreatLevel = SecurityProtocol._currentThreatLevel;
console.log(`Created security protocol for area: ${area}`);
}
// Static method accessible directly on the class
static raiseGlobalThreatLevel(): void {
if (this._currentThreatLevel < this.LEVEL_CRITICAL) {
this._currentThreatLevel++;
console.log(`WARNING: Raised global threat level to ${this._currentThreatLevel}`);
// Calling another static method
this.notifyAboutThreatLevel();
} else {
console.log("WARNING: Maximum threat level already reached!");
}
}
// Another static method
static lowerGlobalThreatLevel(): void {
if (this._currentThreatLevel > this.LEVEL_MINIMAL) {
this._currentThreatLevel--;
console.log(`Lowered global threat level to ${this._currentThreatLevel}`);
} else {
console.log("Threat level is already at minimum.");
}
}
// Static getter
static get currentThreatLevel(): number {
return this._currentThreatLevel;
}
// Private static method
private static notifyAboutThreatLevel(): void {
console.log(`Notification: Current park threat level: ${this._currentThreatLevel}`);
}
// Instance method using static properties
updateLocalThreatLevel(): void {
// Updating the local level based on the global level
this.localThreatLevel = SecurityProtocol._currentThreatLevel;
console.log(`Area ${this.area}: updated threat level to ${this.localThreatLevel}`);
}
get securityStatus(): string {
const levels = [
"UNKNOWN",
"MINIMAL",
"LOW",
"MEDIUM",
"HIGH",
"CRITICAL"
];
return `Area: ${this.area}, Threat level: ${levels[this.localThreatLevel]}`;
}
}
// Using static properties and methods - without creating instances!
console.log("Default threat level:", SecurityProtocol.currentThreatLevel);
// Calling a static method directly on the class
SecurityProtocol.raiseGlobalThreatLevel();
SecurityProtocol.raiseGlobalThreatLevel();
// Creating instances of the class
const centralProtocol = new SecurityProtocol("Operations Center");
const enclosureProtocol = new SecurityProtocol("T-Rex Enclosure");
// Displaying the security status
console.log(centralProtocol.securityStatus);
console.log(enclosureProtocol.securityStatus);
// Raising the global threat level again
SecurityProtocol.raiseGlobalThreatLevel();
// Updating local threat levels
centralProtocol.updateLocalThreatLevel();
enclosureProtocol.updateLocalThreatLevel();
// Checking updated statuses
console.log(centralProtocol.securityStatus);
console.log(enclosureProtocol.securityStatus);Dans l'exemple ci-dessus :
- Les constantes de niveau de menace sont des propriétés statiques, accessibles directement via la classe
- La propriété statique
_currentThreatLevelest partagée entre toutes les instances - Les méthodes statiques peuvent modifier les propriétés statiques et appeler d'autres méthodes statiques
- Les instances de la classe peuvent mettre à jour leur état interne en fonction des propriétés statiques
Quand utiliser les éléments statiques
Les éléments statiques sont particulièrement utiles dans les cas suivants :
- Constantes et configuration - Des valeurs qui restent inchangées pour toutes les instances d'une classe
- État global - Lorsqu'on a besoin d'une valeur partagée par toutes les instances
- Méthodes utilitaires - Des fonctions auxiliaires qui n'ont pas besoin de l'état d'une instance
- Méthodes fabriques - Des façons alternatives de créer des instances de la classe
Voici un exemple plus élaboré montrant différents usages des éléments statiques :
class GeneticRegistry {
// Static constants
static readonly NUCLEOTIDE_BASE = ["A", "C", "G", "T"];
static readonly MIN_DNA_LENGTH = 1000000;
// Global state
private static _registeredSpeciesCount: number = 0;
private static _speciesRegistrations: Map<string, string> = new Map();
// Instance properties
private id: string;
private dnaSequence: string;
private name: string;
constructor(name: string, dnaSequence: string) {
if (dnaSequence.length < GeneticRegistry.MIN_DNA_LENGTH) {
throw new Error(`DNA sequence is too short. Minimum required: ${GeneticRegistry.MIN_DNA_LENGTH} base pairs.`);
}
this.name = name;
this.dnaSequence = dnaSequence;
this.id = GeneticRegistry.generateId(name);
// Registering a new species
GeneticRegistry._speciesRegistrations.set(this.id, name);
GeneticRegistry._registeredSpeciesCount++;
}
// Utility method - creates an ID based on name
private static generateId(name: string): string {
const timestamp = Date.now();
const cleanName = name.toLowerCase().replace(/[^a-z0-9]/g, "");
return `DNA-${cleanName}-${timestamp}`;
}
// Factory method - creates an instance with random DNA
static createTestSpecies(name: string): GeneticRegistry {
const dnaLength = this.MIN_DNA_LENGTH + Math.floor(Math.random() * 500000);
let sequence = "";
for (let i = 0; i < dnaLength; i++) {
const randomIndex = Math.floor(Math.random() * this.NUCLEOTIDE_BASE.length);
sequence += this.NUCLEOTIDE_BASE[randomIndex];
}
return new GeneticRegistry(name, sequence);
}
// Utility method - verifies the correctness of a DNA sequence
static verifySequence(sequence: string): boolean {
if (sequence.length < this.MIN_DNA_LENGTH) return false;
// Checks if the sequence contains only allowed nucleotides
for (const nucleotide of sequence) {
if (!this.NUCLEOTIDE_BASE.includes(nucleotide)) {
return false;
}
}
return true;
}
// Getter for the static property
static get registeredSpeciesCount(): number {
return this._registeredSpeciesCount;
}
// Static method returning all registered species
static getAllSpecies(): string[] {
return Array.from(this._speciesRegistrations.values());
}
// Instance method using static fields
analyzeSequence(): { proportions: Record<string, number>, length: number } {
const proportions: Record<string, number> = {};
// Initializing counters for each nucleotide
GeneticRegistry.NUCLEOTIDE_BASE.forEach(n => {
proportions[n] = 0;
});
// Counting nucleotides
for (const nucleotide of this.dnaSequence) {
proportions[nucleotide]++;
}
// Converting to percentages
GeneticRegistry.NUCLEOTIDE_BASE.forEach(n => {
proportions[n] = Number((proportions[n] / this.dnaSequence.length * 100).toFixed(2));
});
return {
proportions,
length: this.dnaSequence.length
};
}
// Instance getters
get id(): string {
return this.id;
}
get speciesName(): string {
return this.name;
}
}
// Using static methods and properties
console.log("Minimum DNA length:", GeneticRegistry.MIN_DNA_LENGTH);
console.log("Available nucleotides:", GeneticRegistry.NUCLEOTIDE_BASE.join(", "));
// Verifying a sample sequence
const exampleSequence = "ACGTACGTACGT".repeat(100000); // Repeating to reach min. length
console.log("Sequence verification:", GeneticRegistry.verifySequence(exampleSequence));
// Creating instances using the factory method
const trex = GeneticRegistry.createTestSpecies("Tyrannosaurus Rex");
const raptor = GeneticRegistry.createTestSpecies("Velociraptor");
const trike = GeneticRegistry.createTestSpecies("Triceratops");
// Checking how many species have been registered
console.log("Number of registered species:", GeneticRegistry.registeredSpeciesCount);
console.log("Species list:", GeneticRegistry.getAllSpecies());
// Using instance methods
const trexAnalysis = trex.analyzeSequence();
console.log(`Analysis: ${trex.speciesName} (ID: ${trex.id}):`);
console.log(`Sequence length: ${trexAnalysis.length} base pairs`);
console.log("Nucleotide proportions:", trexAnalysis.proportions);Cet exemple illustre :
- L'utilisation de constantes statiques (
NUCLEOTIDE_BASE,MIN_DNA_LENGTH) - Un état global qui suit le nombre et l'enregistrement des espèces
- Des méthodes utilitaires statiques comme
verifySequenceetgenerateId - Une méthode fabrique
createTestSpeciesqui crée des instances avec des données aléatoires - Comment les méthodes d'instance peuvent utiliser les propriétés statiques
Classes et méthodes abstraites
Les classes abstraites en TypeScript définissent un modèle qui doit être implémenté par les classes qui en héritent. On ne peut pas créer directement une instance d'une classe abstraite - elle sert de « plan » de base pour d'autres classes.
Les méthodes abstraites, définies dans une classe abstraite, doivent être implémentées par les classes qui en héritent. Elles définissent un contrat précisant quelles méthodes doivent être disponibles, mais ne contiennent pas leur propre implémentation.
Les bases des classes abstraites
Voyons comment utiliser les classes abstraites dans le contexte de Jurassic Park :
// Abstract base class for all dinosaurs
abstract class Dinosaur {
// Properties common to all dinosaurs
private _id: string;
protected _name: string;
protected _species: string;
protected _age: number;
protected _weight: number;
constructor(id: string, name: string, species: string, age: number, weight: number) {
this._id = id;
this._name = name;
this._species = species;
this._age = age;
this._weight = weight;
}
// Getters
get id(): string { return this._id; }
get name(): string { return this._name; }
get species(): string { return this._species; }
get age(): number { return this._age; }
get weight(): number { return this._weight; }
// Methods implemented in all derived classes
abstract calculateCaloricNeeds(): number;
abstract determineThreatLevel(): number;
// Abstract property - must be implemented in derived classes
abstract get dietType(): string;
// Concrete method (not abstract) - available in all derived classes
getBasicData(): string {
return `${this._name} (${this._species}) - ID: ${this._id}, Age: ${this._age} years, Weight: ${this._weight} kg`;
}
// Method using abstract methods
generateReportDinosaur(): string {
const calories = this.calculateCaloricNeeds();
const threatLevel = this.determineThreatLevel();
return `
=== DINOSAUR REPORT ===
${this.getBasicData()}
Diet type: ${this.dietType}
Daily caloric demand: ${calories} kcal
Threat level: ${threatLevel}/10
======================
`;
}
}
// Class inheriting from the abstract class
class PredatoryDinosaur extends Dinosaur {
private _biteForce: number;
private _runSpeed: number;
constructor(
id: string,
name: string,
species: string,
age: number,
weight: number,
biteForce: number,
runSpeed: number
) {
super(id, name, species, age, weight);
this._biteForce = biteForce;
this._runSpeed = runSpeed;
}
// Getters
get biteForce(): number { return this._biteForce; }
get runSpeed(): number { return this._runSpeed; }
// Implementation of abstract property
get dietType(): string {
return "carnivore";
}
// Implementations of abstract methods
calculateCaloricNeeds(): number {
// For predators we use a complex formula
return Math.round(this._weight * 0.6 * (this._runSpeed * 0.2));
}
determineThreatLevel(): number {
// Threat level depends on bite force, speed, and weight
const base = (this._biteForce * 0.7 + this._runSpeed * 0.3) / 100;
return Math.min(10, Math.max(1, Math.round(base)));
}
// Method specific to predators
hunt(): string {
return `${this._name} hunts at speed ${this._runSpeed} km/h and bite force ${this._biteForce} PSI`;
}
}
// Another inheriting class
class HerbivorousDinosaur extends Dinosaur {
private _neckLength: number;
private _armorType: "none" | "light" | "medium" | "heavy";
constructor(
id: string,
name: string,
species: string,
age: number,
weight: number,
neckLength: number,
armorType: "none" | "light" | "medium" | "heavy"
) {
super(id, name, species, age, weight);
this._neckLength = neckLength;
this._armorType = armorType;
}
// Getters
get neckLength(): number { return this._neckLength; }
get armorType(): string { return this._armorType; }
// Implementation of abstract property
get dietType(): string {
return "herbivorous";
}
// Implementations of abstract methods
calculateCaloricNeeds(): number {
// For herbivores we use a simpler formula - they need more calories per kilogram
return Math.round(this._weight * 0.8);
}
determineThreatLevel(): number {
// Threat level is lower for herbivores, but depends on weight and armor type
let base = this._weight / 1000;
// Modifier dependent on armor
const armorModifiers = {
"none": 0,
"light": 1,
"medium": 2,
"heavy": 3
};
base += armorModifiers[this._armorType];
return Math.min(7, Math.max(1, Math.round(base))); // Max. 7 for herbivores
}
// Method specific to herbivores
graze(): string {
const reachHeight = this._neckLength > 2 ? "tall" : "low";
return `${this._name} is grazing, eating plants from ${reachHeight} tree sections`;
}
}
// We cannot create an instance of an abstract class
// const invalid = new Dinosaur("ID", "Name", "Species", 1, 100); // Error!
// Creating instances of derived classes
const trex = new PredatoryDinosaur("T-REX-1", "Rex", "Tyrannosaurus", 8, 7000, 12800, 32);
const stegosaurus = new HerbivorousDinosaur("STEG-1", "Spike", "Stegosaurus", 12, 5000, 1.2, "heavy");
const diplodocus = new HerbivorousDinosaur("DIPL-1", "Dippy", "Diplodocus", 15, 16000, 6.5, "none");
// Using methods implemented in derived classes
console.log(trex.generateReportDinosaur());
console.log(stegosaurus.generateReportDinosaur());
console.log(diplodocus.generateReportDinosaur());
// Using methods specific to a given class
console.log(trex.hunt());
console.log(stegosaurus.graze());
// For both types of dinosaurs we can use base class methods
console.log(trex.getBasicData());
console.log(diplodocus.getBasicData());Dans l'exemple ci-dessus :
Dinosaurest une classe abstraite contenant des propriétés et méthodes communes- Les méthodes abstraites
calculateCaloricNeeds()etdetermineThreatLevel()doivent être implémentées par les classes qui en héritent - La propriété abstraite
dietTypedoit être définie dans les classes dérivées - Les classes
PredatoryDinosauretHerbivorousDinosaurimplémentent les méthodes et propriétés abstraites - On ne peut pas créer directement une instance de la classe
Dinosaur
Applications des classes et méthodes abstraites
Les classes abstraites sont particulièrement utiles dans les cas suivants :
- Définir une interface commune - Spécifier un ensemble cohérent de méthodes pour un groupe de classes apparentées
- Partager du code - Fournir une implémentation commune à des groupes de classes
- Imposer un contrat - Garantir que toutes les classes dérivées implémenteront les méthodes requises
- Créer des hiérarchies de types - Construire des relations complexes entre types
Voyons un exemple plus avancé qui combine classes et méthodes abstraites avec des éléments statiques dans un système de gestion des protocoles de sécurité de Jurassic Park :
// Helper types
type AlertLevel = "normal" | "elevated" | "high" | "critical";
type StatusSystem = "active" | "inactive" | "maintenance" | "failure";
// Interface for monitoring systems
interface MonitoringSystem {
startMonitoring(): void;
stopMonitoring(): void;
getCurrentStatus(): StatusSystem;
}
// Abstract base class for all security systems
abstract class SecuritySystem implements MonitoringSystem {
// Static properties - for all security systems
private static _parkAlertLevel: AlertLevel = "normal";
private static _activeSystems: Set<string> = new Set();
private static _incidents: Array<{date: Date, systemType: string, location: string, description: string}> = [];
// Regular properties
protected _id: string;
protected _location: string;
protected _status: StatusSystem;
protected _isMonitored: boolean;
protected _reviewDate: Date;
constructor(id: string, location: string) {
this._id = id;
this._location = location;
this._status = "inactive";
this._isMonitored = false;
this._reviewDate = new Date();
// System registration
SecuritySystem.registerSystem(id, this.constructor.name);
}
// Static methods
static registerSystem(id: string, systemType: string): void {
console.log(`Registered new security system: ${systemType} (ID: ${id})`);
}
static reportIncident(systemType: string, location: string, description: string): void {
const incident = {
date: new Date(),
systemType,
location,
description
};
this._incidents.push(incident);
console.log(`ALERT: Incident reported at location ${location}: ${description}`);
// Automatically raising the alert level
if (this._parkAlertLevel === "normal") {
this.changeAlertLevel("elevated");
} else if (this._parkAlertLevel === "elevated") {
this.changeAlertLevel("high");
} else if (this._parkAlertLevel === "high") {
this.changeAlertLevel("critical");
}
}
static changeAlertLevel(newLevel: AlertLevel): void {
this._parkAlertLevel = newLevel;
console.log(`WARNING: Changed park alert level to: ${newLevel.toUpperCase()}`);
}
static get alertLevel(): AlertLevel {
return this._parkAlertLevel;
}
static get recentIncidents(): Array<{date: Date, systemType: string, location: string, description: string}> {
// Returning the 5 most recent incidents
return [...this._incidents].slice(-5);
}
// Instance getters
get id(): string { return this._id; }
get location(): string { return this._location; }
get status(): StatusSystem { return this._status; }
// Implementation of MonitoringSystem interface
startMonitoring(): void {
this._isMonitored = true;
SecuritySystem._activeSystems.add(this._id);
console.log(`Monitoring started for system ${this.constructor.name} in location ${this._location}`);
}
stopMonitoring(): void {
this._isMonitored = false;
SecuritySystem._activeSystems.delete(this._id);
console.log(`Monitoring stopped for system ${this.constructor.name} in location ${this._location}`);
}
getCurrentStatus(): StatusSystem {
return this._status;
}
// Abstract methods that must be implemented
abstract start(): void;
abstract stop(): void;
abstract performReview(): void;
// Abstract properties
abstract get systemType(): string;
abstract get alarmPriorityLevel(): number; // 1-10
// Method using abstract properties and methods
generateStatusReport(): string {
return `
=== SECURITY SYSTEM REPORT ===
ID: ${this._id}
Type: ${this.systemType}
Location: ${this._location}
Status: ${this._status}
Monitored: ${this._isMonitored ? "YES" : "NO"}
Alarm priority: ${this.alarmPriorityLevel}/10
Last review: ${this._reviewDate.toLocaleDateString()}
Global alert level: ${SecuritySystem._parkAlertLevel.toUpperCase()}
=================================
`;
}
}
// Derived class - Electric Fence System
class ElectricFenceSystem extends SecuritySystem {
private _voltage: number; // in volts
private _fenceLength: number; // in meters
private _securityType: "standard" | "reinforced" | "ultra-reinforced";
constructor(
id: string,
location: string,
fenceLength: number,
securityType: "standard" | "reinforced" | "ultra-reinforced"
) {
super(id, location);
this._voltage = 0;
this._fenceLength = fenceLength;
this._securityType = securityType;
}
// Implementation of abstract properties
get systemType(): string {
return "Fence Electric";
}
get alarmPriorityLevel(): number {
// Priority depends on the security type
const base = this._securityType === "standard" ? 7 :
this._securityType === "reinforced" ? 8 : 10;
// We take fence length into account - longer ones have higher priority
const modifier = Math.min(2, Math.floor(this._fenceLength / 1000));
return Math.min(10, base + modifier);
}
// Implementation of abstract methods
start(): void {
if (this._status === "maintenance") {
console.log(`ERROR: Cannot start system ${this._id} - is under maintenance`);
return;
}
this._status = "active";
// Voltage depends on the security type
this._voltage = this._securityType === "standard" ? 10000 :
this._securityType === "reinforced" ? 20000 : 30000;
console.log(`Started fence system ${this._id} in location ${this._location}`);
console.log(`Voltage: ${this._voltage}V, Length: ${this._fenceLength}m`);
}
stop(): void {
this._status = "inactive";
this._voltage = 0;
console.log(`Stopped fence system ${this._id} in location ${this._location}`);
// Reporting an incident at high alert level
if (SecuritySystem.alertLevel === "high" || SecuritySystem.alertLevel === "critical") {
SecuritySystem.reportIncident(
this.systemType,
this._location,
`Fence shutdown at high alert level!`
);
}
}
performReview(): void {
const previousStatus = this._status;
this._status = "maintenance";
console.log(`Started fence system review ${this._id}`);
// Simulation of inspection
setTimeout(() => {
this._reviewDate = new Date();
this._status = previousStatus;
console.log(`Completed fence system review ${this._id}`);
}, 2000);
}
// Methods specific to this system type
changeVoltage(newVoltage: number): void {
if (this._status !== "active") {
console.log(`ERROR: Cannot change voltage - system is not active`);
return;
}
this._voltage = newVoltage;
console.log(`Changed fence voltage ${this._id} to ${newVoltage}V`);
}
reportFenceBreach(): void {
this._status = "failure";
SecuritySystem.reportIncident(
this.systemType,
this._location,
`Electric fence breach detected!`
);
}
}
// Another derived class - Video Monitoring System
class VideoMonitoringSystem extends SecuritySystem {
private _cameraCount: number;
private _resolution: "SD" | "HD" | "4K";
private _nightMode: boolean;
constructor(
id: string,
location: string,
cameraCount: number,
resolution: "SD" | "HD" | "4K"
) {
super(id, location);
this._cameraCount = cameraCount;
this._resolution = resolution;
this._nightMode = false;
}
// Implementation of abstract properties
get systemType(): string {
return "Video monitoring";
}
get alarmPriorityLevel(): number {
// Priority depends on the number of cameras and resolution
const base = 5;
// Resolution modifier
const resolutionModifier =
this._resolution === "SD" ? 0 :
this._resolution === "HD" ? 1 : 2;
// Camera count modifier
const cameraModifier = Math.min(2, Math.floor(this._cameraCount / 10));
return Math.min(10, base + resolutionModifier + cameraModifier);
}
// Implementation of abstract methods
start(): void {
this._status = "active";
console.log(`Started monitoring system ${this._id} in location ${this._location}`);
console.log(`Camera count: ${this._cameraCount}, Resolution: ${this._resolution}`);
}
stop(): void {
this._status = "inactive";
console.log(`Stopped monitoring system ${this._id} in location ${this._location}`);
}
performReview(): void {
this._status = "maintenance";
console.log(`Started monitoring system review ${this._id}`);
// In this case, the inspection completes immediately
this._reviewDate = new Date();
this._status = "active";
console.log(`Completed monitoring system review ${this._id}`);
}
// Methods specific to this system type
enableNightMode(): void {
this._nightMode = true;
console.log(`Enabled night mode in monitoring system ${this._id}`);
}
disableNightMode(): void {
this._nightMode = false;
console.log(`Disabled night mode in monitoring system ${this._id}`);
}
detectMotion(area: string): void {
console.log(`System ${this._id}: Motion detected in area ${area}`);
if (SecuritySystem.alertLevel !== "normal") {
SecuritySystem.reportIncident(
this.systemType,
`${this._location} - area ${area}`,
`Detected unauthorized motion!`
);
}
}
}
// Demonstration of Jurassic Park security system
function testSecuritySystem() {
console.log("=== INITIALIZING JURASSIC PARK SECURITY SYSTEMS ===");
// Creating fence systems
const mainFence = new ElectricFenceSystem("FNC-001", "Sector A - Main entrance", 2500, "ultra-reinforced");
const tRexFence = new ElectricFenceSystem("FNC-002", "Sector B - Enclosure T-Rex", 1200, "ultra-reinforced");
const raptorFence = new ElectricFenceSystem("FNC-003", "Sector C - Raptor Enclosure", 800, "reinforced");
// Creating monitoring systems
const mainMonitoring = new VideoMonitoringSystem("CAM-001", "Control center", 20, "4K");
const monitoringTRex = new VideoMonitoringSystem("CAM-002", "Sector B - Enclosure T-Rex", 12, "HD");
const raptorMonitoring = new VideoMonitoringSystem("CAM-003", "Sector C - Raptor Enclosure", 8, "HD");
// Starting all systems
console.log("\n=== STARTING SYSTEMS ===");
mainFence.start();
tRexFence.start();
raptorFence.start();
mainMonitoring.start();
monitoringTRex.start();
raptorMonitoring.start();
// Starting monitoring
console.log("\n=== ACTIVATION MONITORING ===");
mainFence.startMonitoring();
tRexFence.startMonitoring();
raptorFence.startMonitoring();
mainMonitoring.startMonitoring();
monitoringTRex.startMonitoring();
raptorMonitoring.startMonitoring();
// Checking statuses
console.log("\n=== SYSTEM REPORTS ===");
console.log(mainFence.generateStatusReport());
console.log(monitoringTRex.generateStatusReport());
// Simulating an incident
console.log("\n=== SIMULATION INCIDENT ===");
console.log("Current alert level:", SecuritySystem.alertLevel);
raptorMonitoring.detectMotion("South corner");
raptorFence.reportFenceBreach();
// Checking alert level after incidents
console.log("\nCurrent alert level after incidents:", SecuritySystem.alertLevel);
// Displaying recent incidents
console.log("\n=== LAST INCIDENTS ===");
SecuritySystem.recentIncidents.forEach((incident, index) => {
console.log(`${index + 1}. [${incident.date.toLocaleString()}] ${incident.systemType} in ${incident.location}: ${incident.description}`);
});
// Conducting inspection
console.log("\n=== SYSTEM REVIEW ===");
tRexFence.performReview();
mainMonitoring.performReview();
// Manual alert level change
console.log("\n=== NORMALIZATION SITUATION ===");
SecuritySystem.changeAlertLevel("normal");
}
// Running the test
testSecuritySystem();Dans cet exemple avancé :
- Nous utilisons la classe abstraite
SecuritySystemcomme base de tous les systèmes de sécurité - La classe définit des propriétés et méthodes statiques (par ex. le niveau d'alerte du parc, la liste des incidents)
- Les méthodes et propriétés abstraites imposent l'implémentation de fonctionnalités spécifiques dans les classes dérivées
- Les classes dérivées (
ElectricFenceSystemetVideoMonitoringSystem) implémentent les éléments abstraits - Les éléments statiques permettent une coordination centrale (par ex. signaler des incidents et gérer les niveaux d'alerte)
Combiner éléments statiques et abstraits
Les éléments statiques et abstraits peuvent être un outil puissant lorsqu'on les utilise ensemble dans une hiérarchie de classes bien conçue. Voici quelques motifs et exemples de leur application :
1. Classe de base abstraite avec méthodes fabriques statiques
abstract class DinosaurSpecies {
// Static properties
private static _registeredDinosaurs: Map<string, DinosaurSpecies> = new Map();
// Instance properties
private _name: string;
private _eraValue: string;
protected _dietType: "carnivore" | "herbivorous" | "omnivore";
constructor(name: string, era: string, diet: "carnivore" | "herbivorous" | "omnivore") {
this._name = name;
this._eraValue = era;
this._dietType = diet;
// Adding to registry
DinosaurSpecies._registeredDinosaurs.set(name, this);
}
// Static factory method - creates the appropriate species based on diet
static createSpecies(
name: string,
era: string,
diet: "carnivore" | "herbivorous" | "omnivore",
additionalParams: Record<string, any>
): DinosaurSpecies {
if (diet === "carnivore") {
return new CarnivoreSpecies(
name,
era,
additionalParams.biteForce,
additionalParams.runSpeed
);
} else {
return new HerbivoreSpecies(
name,
era,
additionalParams.neckLength || 0,
additionalParams.hasArmor || false
);
}
}
// Static method for retrieving registered species
static getSpecies(name: string): DinosaurSpecies | undefined {
return this._registeredDinosaurs.get(name);
}
static get allSpecies(): string[] {
return Array.from(this._registeredDinosaurs.keys());
}
// Instance getters
get name(): string { return this._name; }
get era(): string { return this._eraValue; }
get dietType(): string { return this._dietType; }
// Abstract methods
abstract behaviorDescription(): string;
abstract estimateWeight(length: number): number;
// Method using abstract methods
generateDescription(): string {
return `${this._name} - dinosaur ${this._dietType} from the ${this._eraValue} era.
${this.behaviorDescription()}`;
}
}
// Derived classes
class CarnivoreSpecies extends DinosaurSpecies {
private _biteForce: number; // in PSI
private _runSpeed: number; // in km/h
constructor(name: string, era: string, biteForce: number, runSpeed: number) {
super(name, era, "carnivore");
this._biteForce = biteForce;
this._runSpeed = runSpeed;
}
// Getters
get biteForce(): number { return this._biteForce; }
get runSpeed(): number { return this._runSpeed; }
// Implementation of abstract methods
behaviorDescription(): string {
return `Hunts at speed ${this._runSpeed} km/h and bite force ${this._biteForce} PSI.`;
}
estimateWeight(length: number): number {
// Approximate formula for predators
return length * length * 100;
}
}
class HerbivoreSpecies extends DinosaurSpecies {
private _neckLength: number; // in meters
private _hasArmor: boolean;
constructor(name: string, era: string, neckLength: number, hasArmor: boolean) {
super(name, era, "herbivorous");
this._neckLength = neckLength;
this._hasArmor = hasArmor;
}
// Getters
get neckLength(): number { return this._neckLength; }
get hasArmor(): boolean { return this._hasArmor; }
// Implementation of abstract methods
behaviorDescription(): string {
const neckDescription = this._neckLength > 3
? `Has a long neck (${this._neckLength}m) allowing it to eat tall vegetation.`
: "Feeds on low vegetation.";
const armorDescription = this._hasArmor
? "Has armor for protection against predators."
: "Does not have protective armor.";
return `${neckDescription} ${armorDescription}`;
}
estimateWeight(length: number): number {
// Approximate formula for herbivores (usually heavier)
let weight = length * length * 150;
// Additional weight for armor
if (this._hasArmor) {
weight *= 1.3;
}
return weight;
}
}
// Usage
function testDinosaurSpecies() {
// Creating species using the factory method
DinosaurSpecies.createSpecies(
"Tyrannosaurus Rex",
"late Cretaceous",
"carnivore",
{ biteForce: 12800, runSpeed: 32 }
);
DinosaurSpecies.createSpecies(
"Velociraptor",
"late Cretaceous",
"carnivore",
{ biteForce: 2000, runSpeed: 64 }
);
DinosaurSpecies.createSpecies(
"Brachiosaurus",
"late Jurassic",
"herbivorous",
{ neckLength: 9, hasArmor: false }
);
DinosaurSpecies.createSpecies(
"Stegosaurus",
"late Jurassic",
"herbivorous",
{ neckLength: 0.5, hasArmor: true }
);
// Accessing registered species
console.log("Available species:", DinosaurSpecies.allSpecies);
// Retrieving species information
const trex = DinosaurSpecies.getSpecies("Tyrannosaurus Rex");
const brach = DinosaurSpecies.getSpecies("Brachiosaurus");
if (trex) {
console.log(trex.generateDescription());
console.log(`Estimated weight (12m long): ${trex.estimateWeight(12)} kg`);
}
if (brach) {
console.log(brach.generateDescription());
console.log(`Estimated weight (25m long): ${brach.estimateWeight(25)} kg`);
}
// Type checking
const steg = DinosaurSpecies.getSpecies("Stegosaurus") as HerbivoreSpecies;
if (steg && steg instanceof HerbivoreSpecies) {
console.log(`Stegosaurus has armor: ${steg.hasArmor ? "YES" : "NO"}`);
}
const raptor = DinosaurSpecies.getSpecies("Velociraptor") as CarnivoreSpecies;
if (raptor && raptor instanceof CarnivoreSpecies) {
console.log(`Velociraptor - run speed: ${raptor.runSpeed} km/h`);
}
}
testDinosaurSpecies();2. Méthodes statiques abstraites
Depuis la version 4.0 de TypeScript, il est possible de définir des méthodes statiques abstraites. Cela permet de créer des hiérarchies de classes où les classes dérivées doivent implémenter des méthodes statiques précises :
abstract class LocationSystem {
// Instance properties
protected _id: string;
protected _name: string;
constructor(id: string, name: string) {
this._id = id;
this._name = name;
}
// Abstract static method that derived classes must implement
static abstract generateLocationId(type: string, num: number): string;
// Regular abstract instance method
abstract getLocationInfo(): Record<string, any>;
// Instance method
generateReport(): string {
const info = this.getLocationInfo();
let report = `=== REPORT LOCATION: ${this._name} (ID: ${this._id}) ===\n`;
for (const [key, value] of Object.entries(info)) {
report += `${key}: ${value}\n`;
}
return report;
}
}
class DinosaurEnclosure extends LocationSystem {
private _species: string;
private _area: number; // in hectares
private _specimenCount: number;
constructor(num: number, name: string, species: string, area: number, specimenCount: number) {
// Generating ID for the enclosure
const id = DinosaurEnclosure.generateLocationId("enclosure", num);
super(id, name);
this._species = species;
this._area = area;
this._specimenCount = specimenCount;
}
// Implementation of abstract static method
static generateLocationId(type: string, num: number): string {
return `${type.toUpperCase()}-${num.toString().padStart(3, '0')}`;
}
// Implementation of abstract instance method
getLocationInfo(): Record<string, any> {
return {
type: "Dinosaur enclosure",
species: this._species,
area: `${this._area} ha`,
specimenCount: this._specimenCount,
populationDensity: `${(this._specimenCount / this._area).toFixed(2)} spec./ha`
};
}
// Methods specific to this class
addSpecimen(): void {
this._specimenCount++;
console.log(`Added new specimen to enclosure ${this._name}. New count: ${this._specimenCount}`);
}
removeSpecimen(): boolean {
if (this._specimenCount > 0) {
this._specimenCount--;
console.log(`Removed specimen from enclosure ${this._name}. New count: ${this._specimenCount}`);
return true;
}
console.log(`Error: Cannot remove specimen from enclosure ${this._name} - no specimens.`);
return false;
}
}
class TouristAttraction extends LocationSystem {
private _attractionType: string;
private _capacity: number;
private _waitingTime: number; // in minutes
constructor(num: number, name: string, attractionType: string, capacity: number) {
// Generating ID for the attraction
const id = TouristAttraction.generateLocationId("attraction", num);
super(id, name);
this._attractionType = attractionType;
this._capacity = capacity;
this._waitingTime = 0;
}
// Implementation of abstract static method
static generateLocationId(type: string, num: number): string {
// Different ID format for attractions
return `${type.substring(0, 3).toUpperCase()}${num.toString().padStart(4, '0')}`;
}
// Implementation of abstract instance method
getLocationInfo(): Record<string, any> {
return {
type: "Tourist attraction",
category: this._attractionType,
capacity: this._capacity,
waitingTime: `${this._waitingTime} min`
};
}
// Methods specific to this class
updateWaitingTime(newWaitingTime: number): void {
this._waitingTime = newWaitingTime;
console.log(`Updated waiting time for ${this._name}: ${this._waitingTime} min`);
}
}
// Application
function testLocationSystem() {
// Creating enclosures
const tRexEnclosure = new DinosaurEnclosure(1, "T-Rex Kingdom", "Tyrannosaurus Rex", 5, 1);
const raptorEnclosure = new DinosaurEnclosure(2, "Raptor Valley", "Velociraptor", 3, 6);
// Creating attractions
const visitorCenter = new TouristAttraction(101, "Genetics Center", "educational", 500);
const jeepSafari = new TouristAttraction(102, "Jurassic Safari", "ride", 50);
// Displaying reports
console.log(tRexEnclosure.generateReport());
console.log(raptorEnclosure.generateReport());
console.log(visitorCenter.generateReport());
console.log(jeepSafari.generateReport());
// Performing operations
raptorEnclosure.addSpecimen();
raptorEnclosure.addSpecimen();
jeepSafari.updateWaitingTime(45);
// Checking updated data
console.log(raptorEnclosure.generateReport());
console.log(jeepSafari.generateReport());
// Demonstration of different ID formats generated by static method implementations
console.log("Enclosure ID format:", DinosaurEnclosure.generateLocationId("enclosure", 42));
console.log("Attraction ID format:", TouristAttraction.generateLocationId("attraction", 42));
}
testLocationSystem();Résumé
Dans cet exercice, nous avons découvert deux mécanismes puissants de TypeScript :
Propriétés et méthodes statiques :
- Appartiennent à la classe, et non aux instances
- Permettent de partager des données et des fonctionnalités entre toutes les instances
- Idéales pour définir des constantes, un état global et des méthodes utilitaires
- Accessibles directement via le nom de la classe, sans créer d'instance
Classes et méthodes abstraites :
- Définissent un « modèle » ou un « contrat » qui doit être implémenté par les classes qui en héritent
- Ne peuvent pas être instanciées directement
- Imposent l'implémentation de méthodes précises dans les classes dérivées
- Permettent de partager des fonctionnalités communes au sein d'une hiérarchie de classes
En combinant ces concepts, nous pouvons créer des systèmes élégants, modulaires et sûrs en matière de types, parfaits pour modéliser des relations et processus complexes, comme ceux du système de gestion de Jurassic Park.
Le Dr Henry Wu le résumerait ainsi : « Dans la nature comme en programmation, il y a de la beauté dans la structure et l'ordre. Les éléments statiques assurent la cohérence de toute l'espèce, tandis que les concepts abstraits forment le plan de base que chaque organisme doit implémenter à sa manière. Ensemble, ils créent une harmonie parfaite - avec les protections adéquates, bien sûr... dans la plupart des cas. »
Code de cette leçon : index.ts
// Static properties et abstract classes - Parc Jurassique
console.log("=== STATIC PROPERTIES AND ABSTRACT CLASSES ===\n");
// ===========================================
// 1. Classe abstraite Dinosaur
// ===========================================
abstract class Dinosaur {
// Compteur statique pour tous les dinosaures
static totalCount: number = 0;
static readonly PARK_NAME: string = "Jurassic World";
// Méthode fabrique statique
static createId(): string {
return `DINO-${String(++Dinosaur.totalCount).padStart(4, "0")}`;
}
// Champs d'instance
readonly id: string;
name: string;
protected weight: number;
constructor(name: string, weight: number) {
this.id = Dinosaur.createId();
this.name = name;
this.weight = weight;
}
// Méthode abstraite - chaque espèce doit l'implémenter
abstract makeSound(): string;
abstract getDangerLevel(): number;
// Méthode commune
getProfile(): string {
return `[${this.id}] ${this.name} - ${this.weight}kg`;
}
}
// ===========================================
// 2. Implémentations des classes concrètes
// ===========================================
class TRex extends Dinosaur {
private biteForce: number;
constructor(name: string, weight: number, biteForce: number) {
super(name, weight);
this.biteForce = biteForce;
}
makeSound(): string {
return "ROOOOAAAR!";
}
getDangerLevel(): number {
return 10;
}
}
class Triceratops extends Dinosaur {
private hornLength: number;
constructor(name: string, weight: number, hornLength: number) {
super(name, weight);
this.hornLength = hornLength;
}
makeSound(): string {
return "BRRRRR!";
}
getDangerLevel(): number {
return 4;
}
}
// ===========================================
// 3. Méthode fabrique statique
// ===========================================
class DinosaurFactory {
static registry: Map<string, Dinosaur> = new Map();
static create(type: "trex" | "triceratops", name: string): Dinosaur {
let dino: Dinosaur;
if (type === "trex") {
dino = new TRex(name, 8000, 12800);
} else {
dino = new Triceratops(name, 6000, 90);
}
DinosaurFactory.registry.set(dino.id, dino);
return dino;
}
static getAll(): Dinosaur[] {
return Array.from(DinosaurFactory.registry.values());
}
}
// ===========================================
// Test
// ===========================================
const rex = DinosaurFactory.create("trex", "Rexy");
const trike = DinosaurFactory.create("triceratops", "Cera");
const rex2 = DinosaurFactory.create("trex", "Buck");
console.log("Park:", Dinosaur.PARK_NAME);
console.log("Nombre de dinosaures:", Dinosaur.totalCount);
console.log("");
DinosaurFactory.getAll().forEach(dino => {
console.log(dino.getProfile());
console.log(" Son:", dino.makeSound());
console.log(" Danger:", dino.getDangerLevel(), "/10");
});
// On ne peut pas créer d'instance d'une classe abstraite :
// const dino = new Dinosaur("Test", 100); // Error!
console.log("\nUne classe abstraite ne peut pas être instanciée directement.");Entrées de la documentation utilisées dans cette leçon
Tu as repéré une erreur dans cette leçon ?
Teste tes connaissances
Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.
1. Qu'est-ce qu'une classe abstraite en TypeScript ?
2. En quoi les propriétés statiques diffèrent-elles des propriétés ordinaires dans une classe ?
Tâches pratiques dans le jeu
- Éditeur de code
Implémente des classes avec des propriétés statiques et abstraites.
- Clique dans l'ordre
Range les éléments de la déclaration d'une classe abstraite :
- Éditeur de code
Crée des classes avec différents modificateurs d'accès pour le système du parc