Kurs JavaScript i TypeScript · Moduł 9: Wzorce projektowe i architektura
Wzorce projektowe w JavaScript/TypeScript - Module, Factory i Observer
W tej lekcji6
UWAGA: Materiał rozbudowany - Plan nauki
Ten moduł zawiera bardzo rozbudowany materiał edukacyjny. Nie musisz przyswajać wszystkiego naraz! Oto sugerowana kolejność nauki:
Etap 1 - Fundamenty (priorytet: wysoki)
- Module Pattern i Revealing Module Pattern
- Factory Pattern
- Observer Pattern
- Singleton Pattern
Etap 2 - Architektura (priorytet: średni)
- Zasady SOLID
- Dependency Injection i Event Bus
Etap 3 - Programowanie funkcyjne i stan (priorytet: średni)
- Czyste funkcje, niemutowalność, currying i kompozycja
- Wzorce zarządzania stanem: Flux, Event Sourcing, maszyny stanów
Etap 4 - Wydajność i praktyka (do nauki w miarę potrzeb)
- Code splitting, tree shaking i lazy loading
- Optymalizacja bundla
- Architektura event-driven i projekt końcowy
Wskazówki:
- Przyswajaj materiał po kolei, dział po dziale
- Po każdym wzorcu zrób przerwę i przećwicz go samodzielnie
- Wracaj do trudniejszych tematów po czasie
- Nie przeskakuj fundamentów - są kluczowe dla zrozumienia reszty
- Zaawansowane wzorce możesz studiować w miarę potrzeb w projektach
Pamiętaj: lepiej dobrze zrozumieć podstawy niż pobieżnie przejrzeć wszystko!
Tak jak starożytni architekci wykorzystywali sprawdzone wzorce konstrukcyjne do budowania trwałych świątyń, współcześni programiści używają wzorców projektowych do tworzenia solidnego, skalowalnego kodu. W tej lekcji poznamy cztery fundamentalne wzorce: Module Pattern, Revealing Module Pattern, Factory Pattern oraz Observer Pattern, które stanowią podstawę wielu nowoczesnych aplikacji JavaScript i TypeScript.
Module Pattern - Enkapsulacja i prywatność
Module Pattern to jeden z najważniejszych wzorców w JavaScript, który pozwala na enkapsulację kodu i tworzenie prywatnych zmiennych oraz metod. Przed wprowadzeniem modułów ES6 był to główny sposób organizowania kodu w modułach.
Klasyczna implementacja Module Pattern
// Przykład prostego modułu kalkulatora
const Calculator = (function() {
// Prywatne zmienne i funkcje
let result = 0;
function validateNumber(num) {
if (typeof num !== 'number' || isNaN(num)) {
throw new Error('Podana wartość nie jest liczbą');
}
}
function logOperation(operation, num) {
console.log(`Wykonano operację: ${operation} ${num}`);
}
// Publiczny interfejs
return {
add: function(num) {
validateNumber(num);
result += num;
logOperation('dodawanie', num);
return this;
},
subtract: function(num) {
validateNumber(num);
result -= num;
logOperation('odejmowanie', num);
return this;
},
multiply: function(num) {
validateNumber(num);
result *= num;
logOperation('mnożenie', num);
return this;
},
divide: function(num) {
validateNumber(num);
if (num === 0) {
throw new Error('Nie można dzielić przez zero');
}
result /= num;
logOperation('dzielenie', num);
return this;
},
getResult: function() {
return result;
},
reset: function() {
result = 0;
console.log('Kalkulator został zresetowany');
return this;
}
};
})();
// Użycie
Calculator
.add(10)
.multiply(2)
.subtract(5)
.divide(3);
console.log(Calculator.getResult()); // 5Module Pattern z parametrami
// Moduł do zarządzania stanem aplikacji
const StateManager = (function(initialState = {}) {
// Prywatny stan
let state = { ...initialState };
let listeners = [];
// Prywatne funkcje pomocnicze
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function notifyListeners(action, newState) {
listeners.forEach(listener => {
if (typeof listener === 'function') {
listener(action, deepClone(newState));
}
});
}
// Publiczny interfejs
return {
getState: function(key) {
if (key) {
return deepClone(state[key]);
}
return deepClone(state);
},
setState: function(key, value) {
const oldValue = state[key];
state[key] = value;
notifyListeners({
type: 'STATE_CHANGED',
key: key,
oldValue: oldValue,
newValue: value
}, state);
return this;
},
updateState: function(updates) {
const oldState = deepClone(state);
state = { ...state, ...updates };
notifyListeners({
type: 'STATE_UPDATED',
oldState: oldState,
newState: deepClone(state)
}, state);
return this;
},
subscribe: function(listener) {
if (typeof listener === 'function') {
listeners.push(listener);
}
// Zwracamy funkcję do odsubskrybowania
return function unsubscribe() {
const index = listeners.indexOf(listener);
if (index > -1) {
listeners.splice(index, 1);
}
};
},
reset: function() {
const oldState = deepClone(state);
state = { ...initialState };
notifyListeners({
type: 'STATE_RESET',
oldState: oldState
}, state);
return this;
}
};
})({ theme: 'light', language: 'pl' });
// Użycie
const unsubscribe = StateManager.subscribe((action, newState) => {
console.log('Stan się zmienił:', action);
});
StateManager
.setState('user', { name: 'Jan', age: 30 })
.updateState({ theme: 'dark', notifications: true });Revealing Module Pattern - Ulepszona enkapsulacja
Revealing Module Pattern to ewolucja Module Pattern, która zapewnia większą czytelność i lepsze rozdzielenie między funkcjami prywatnymi a publicznymi.
Podstawowa implementacja Revealing Module Pattern
// Moduł do zarządzania produktami w sklepie
const ProductManager = (function() {
// Prywatne zmienne
let products = [];
let nextId = 1;
// Prywatne funkcje
function generateId() {
return nextId++;
}
function validateProduct(product) {
if (!product.name || typeof product.name !== 'string') {
throw new Error('Nazwa produktu jest wymagana i musi być tekstem');
}
if (!product.price || typeof product.price !== 'number' || product.price <= 0) {
throw new Error('Cena produktu musi być liczbą większą od zera');
}
return true;
}
function findProductIndex(id) {
return products.findIndex(product => product.id === id);
}
function sortProductsByPrice(ascending = true) {
return products.slice().sort((a, b) => {
return ascending ? a.price - b.price : b.price - a.price;
});
}
function filterProductsByCategory(category) {
return products.filter(product =>
product.category && product.category.toLowerCase() === category.toLowerCase()
);
}
// Publiczne funkcje
function addProduct(productData) {
validateProduct(productData);
const product = {
id: generateId(),
name: productData.name,
price: productData.price,
category: productData.category || 'uncategorized',
description: productData.description || '',
inStock: productData.inStock !== false,
createdAt: new Date().toISOString()
};
products.push(product);
console.log(`Dodano produkt: ${product.name}`);
return product.id;
}
function removeProduct(id) {
const index = findProductIndex(id);
if (index === -1) {
throw new Error(`Produkt o ID ${id} nie został znaleziony`);
}
const removedProduct = products.splice(index, 1)[0];
console.log(`Usunięto produkt: ${removedProduct.name}`);
return removedProduct;
}
function updateProduct(id, updates) {
const index = findProductIndex(id);
if (index === -1) {
throw new Error(`Produkt o ID ${id} nie został znaleziony`);
}
const updatedProduct = { ...products[index], ...updates };
validateProduct(updatedProduct);
products[index] = updatedProduct;
console.log(`Zaktualizowano produkt: ${updatedProduct.name}`);
return updatedProduct;
}
function getProduct(id) {
const product = products.find(p => p.id === id);
return product ? { ...product } : null;
}
function getAllProducts() {
return products.map(product => ({ ...product }));
}
function getProductsByCategory(category) {
return filterProductsByCategory(category).map(product => ({ ...product }));
}
function getProductsSortedByPrice(ascending = true) {
return sortProductsByPrice(ascending).map(product => ({ ...product }));
}
function getProductCount() {
return products.length;
}
function clearAllProducts() {
const count = products.length;
products = [];
nextId = 1;
console.log(`Usunięto wszystkie produkty (${count})`);
}
// Revealing - udostępnienie publicznych metod
return {
add: addProduct,
remove: removeProduct,
update: updateProduct,
get: getProduct,
getAll: getAllProducts,
getByCategory: getProductsByCategory,
getSortedByPrice: getProductsSortedByPrice,
count: getProductCount,
clear: clearAllProducts
};
})();
// Użycie
const laptopId = ProductManager.add({
name: 'Laptop Dell XPS 13',
price: 4500,
category: 'Elektronika',
description: 'Wysokiej jakości laptop ultrabook'
});
const phoneId = ProductManager.add({
name: 'iPhone 15 Pro',
price: 5500,
category: 'Elektronika'
});
console.log('Produkty elektroniczne:', ProductManager.getByCategory('Elektronika'));
console.log('Produkty posortowane:', ProductManager.getSortedByPrice());TypeScript z Revealing Module Pattern
// Interfejsy dla lepszej typizacji
interface User {
id: number;
email: string;
name: string;
role: 'admin' | 'user' | 'moderator';
isActive: boolean;
lastLogin?: Date;
}
interface UserCreateData {
email: string;
name: string;
role?: User['role'];
}
interface UserUpdateData {
name?: string;
role?: User['role'];
isActive?: boolean;
}
// Moduł zarządzania użytkownikami w TypeScript
const UserManager = (function(): {
createUser: (userData: UserCreateData) => number;
getUserById: (id: number) => User | null;
updateUser: (id: number, updates: UserUpdateData) => User | null;
deleteUser: (id: number) => boolean;
getAllUsers: () => User[];
getActiveUsers: () => User[];
getUsersByRole: (role: User['role']) => User[];
markUserLogin: (id: number) => boolean;
getUserCount: () => number;
} {
// Prywatne zmienne
let users: User[] = [];
let nextId: number = 1;
// Prywatne funkcje
function generateId(): number {
return nextId++;
}
function validateEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function findUserIndex(id: number): number {
return users.findIndex(user => user.id === id);
}
function isEmailTaken(email: string, excludeId?: number): boolean {
return users.some(user =>
user.email.toLowerCase() === email.toLowerCase() &&
user.id !== excludeId
);
}
function createUserObject(userData: UserCreateData): User {
return {
id: generateId(),
email: userData.email.toLowerCase(),
name: userData.name,
role: userData.role || 'user',
isActive: true,
lastLogin: undefined
};
}
// Publiczne funkcje
function createUser(userData: UserCreateData): number {
if (!validateEmail(userData.email)) {
throw new Error('Nieprawidłowy format email');
}
if (isEmailTaken(userData.email)) {
throw new Error('Użytkownik z tym emailem już istnieje');
}
if (!userData.name || userData.name.trim().length < 2) {
throw new Error('Nazwa użytkownika musi mieć co najmniej 2 znaki');
}
const user = createUserObject(userData);
users.push(user);
console.log(`Utworzono użytkownika: ${user.name} (${user.email})`);
return user.id;
}
function getUserById(id: number): User | null {
const user = users.find(u => u.id === id);
return user ? { ...user } : null;
}
function updateUser(id: number, updates: UserUpdateData): User | null {
const index = findUserIndex(id);
if (index === -1) {
return null;
}
const currentUser = users[index];
const updatedUser: User = {
...currentUser,
...updates
};
if (updates.name && updates.name.trim().length < 2) {
throw new Error('Nazwa użytkownika musi mieć co najmniej 2 znaki');
}
users[index] = updatedUser;
console.log(`Zaktualizowano użytkownika: ${updatedUser.name}`);
return { ...updatedUser };
}
function deleteUser(id: number): boolean {
const index = findUserIndex(id);
if (index === -1) {
return false;
}
const deletedUser = users.splice(index, 1)[0];
console.log(`Usunięto użytkownika: ${deletedUser.name}`);
return true;
}
function getAllUsers(): User[] {
return users.map(user => ({ ...user }));
}
function getActiveUsers(): User[] {
return users.filter(user => user.isActive).map(user => ({ ...user }));
}
function getUsersByRole(role: User['role']): User[] {
return users.filter(user => user.role === role).map(user => ({ ...user }));
}
function markUserLogin(id: number): boolean {
const index = findUserIndex(id);
if (index === -1) {
return false;
}
users[index].lastLogin = new Date();
return true;
}
function getUserCount(): number {
return users.length;
}
// Revealing - eksponowanie publicznych metod
return {
createUser,
getUserById,
updateUser,
deleteUser,
getAllUsers,
getActiveUsers,
getUsersByRole,
markUserLogin,
getUserCount
};
})();
// Użycie z TypeScript
const adminId = UserManager.createUser({
email: 'admin@example.com',
name: 'Administrator',
role: 'admin'
});
const userId = UserManager.createUser({
email: 'user@example.com',
name: 'Jan Kowalski'
});
console.log('Administratorzy:', UserManager.getUsersByRole('admin'));
console.log('Aktywni użytkownicy:', UserManager.getActiveUsers());Factory Pattern - Tworzenie obiektów
Factory Pattern to wzorzec kreacyjny, który pozwala na tworzenie obiektów bez określania konkretnej klasy obiektu, który ma zostać utworzony. Jest szczególnie przydatny, gdy mamy różne typy obiektów o podobnej strukturze.
Prosty Factory Pattern
// Factory do tworzenia różnych typów pojazdów
class VehicleFactory {
static createVehicle(type, options = {}) {
switch (type.toLowerCase()) {
case 'car':
return new Car(options);
case 'motorcycle':
return new Motorcycle(options);
case 'truck':
return new Truck(options);
case 'bicycle':
return new Bicycle(options);
default:
throw new Error(`Nieznany typ pojazdu: ${type}`);
}
}
static getSupportedTypes() {
return ['car', 'motorcycle', 'truck', 'bicycle'];
}
}
// Klasy bazowe
class Vehicle {
constructor(options = {}) {
this.brand = options.brand || 'Unknown';
this.model = options.model || 'Unknown';
this.year = options.year || new Date().getFullYear();
this.color = options.color || 'white';
this.maxSpeed = options.maxSpeed || 0;
}
start() {
console.log(`${this.brand} ${this.model} został uruchomiony`);
}
stop() {
console.log(`${this.brand} ${this.model} został zatrzymany`);
}
getInfo() {
return `${this.brand} ${this.model} (${this.year}) - ${this.color}`;
}
}
class Car extends Vehicle {
constructor(options = {}) {
super(options);
this.type = 'Samochód';
this.doors = options.doors || 4;
this.fuelType = options.fuelType || 'benzyna';
this.transmission = options.transmission || 'manual';
}
openTrunk() {
console.log('Bagażnik został otwarty');
}
getDetails() {
return `${this.getInfo()} - ${this.doors} drzwi, ${this.fuelType}, ${this.transmission}`;
}
}
class Motorcycle extends Vehicle {
constructor(options = {}) {
super(options);
this.type = 'Motocykl';
this.engineSize = options.engineSize || 125; // cm³
this.hasSidecar = options.hasSidecar || false;
}
wheelie() {
console.log('Wykonuję wheelie!');
}
getDetails() {
const sidecar = this.hasSidecar ? 'z przyczepką' : 'bez przyczepki';
return `${this.getInfo()} - ${this.engineSize}cm³, ${sidecar}`;
}
}
class Truck extends Vehicle {
constructor(options = {}) {
super(options);
this.type = 'Ciężarówka';
this.loadCapacity = options.loadCapacity || 1000; // kg
this.trailerAttached = options.trailerAttached || false;
}
loadCargo(weight) {
if (weight > this.loadCapacity) {
console.log(`Nie można załadować ${weight}kg. Maksymalna ładowność: ${this.loadCapacity}kg`);
return false;
}
console.log(`Załadowano ${weight}kg cargo`);
return true;
}
getDetails() {
const trailer = this.trailerAttached ? 'z przyczepą' : 'bez przyczepy';
return `${this.getInfo()} - ładowność: ${this.loadCapacity}kg, ${trailer}`;
}
}
class Bicycle extends Vehicle {
constructor(options = {}) {
super(options);
this.type = 'Rower';
this.gears = options.gears || 1;
this.isElectric = options.isElectric || false;
this.maxSpeed = options.maxSpeed || 25;
}
ringBell() {
console.log('Dzyn dzyn!');
}
getDetails() {
const electric = this.isElectric ? 'elektryczny' : 'tradycyjny';
return `${this.getInfo()} - liczba biegów: ${this.gears}, ${electric}`;
}
}
// Użycie Factory Pattern
const vehicles = [
VehicleFactory.createVehicle('car', {
brand: 'Toyota',
model: 'Corolla',
year: 2023,
color: 'niebieski',
doors: 4,
fuelType: 'hybrid'
}),
VehicleFactory.createVehicle('motorcycle', {
brand: 'Harley-Davidson',
model: 'Street 750',
color: 'czarny',
engineSize: 750
}),
VehicleFactory.createVehicle('bicycle', {
brand: 'Trek',
model: 'FX 3',
color: 'czerwony',
gears: 24,
isElectric: false
})
];
vehicles.forEach(vehicle => {
console.log(vehicle.getDetails());
vehicle.start();
});Abstract Factory Pattern
// Interfejsy dla Abstract Factory
interface Button {
render(): string;
onClick(): void;
}
interface Input {
render(): string;
getValue(): string;
setValue(value: string): void;
}
interface Modal {
render(): string;
show(): void;
hide(): void;
}
// Abstract Factory Interface
interface UIFactory {
createButton(text: string): Button;
createInput(placeholder: string): Input;
createModal(title: string): Modal;
}
// Material Design implementacje
class MaterialButton implements Button {
constructor(private text: string) {}
render(): string {
return `<button class="material-button">${this.text}</button>`;
}
onClick(): void {
console.log(`Material button '${this.text}' clicked`);
}
}
class MaterialInput implements Input {
private value: string = '';
constructor(private placeholder: string) {}
render(): string {
return `<input class="material-input" placeholder="${this.placeholder}" />`;
}
getValue(): string {
return this.value;
}
setValue(value: string): void {
this.value = value;
console.log(`Material input value set to: ${value}`);
}
}
class MaterialModal implements Modal {
private isVisible: boolean = false;
constructor(private title: string) {}
render(): string {
return `
<div class="material-modal">
<div class="material-modal-header">${this.title}</div>
<div class="material-modal-content"></div>
</div>
`;
}
show(): void {
this.isVisible = true;
console.log(`Material modal '${this.title}' shown`);
}
hide(): void {
this.isVisible = false;
console.log(`Material modal '${this.title}' hidden`);
}
}
// Bootstrap implementacje
class BootstrapButton implements Button {
constructor(private text: string) {}
render(): string {
return `<button class="btn btn-primary">${this.text}</button>`;
}
onClick(): void {
console.log(`Bootstrap button '${this.text}' clicked`);
}
}
class BootstrapInput implements Input {
private value: string = '';
constructor(private placeholder: string) {}
render(): string {
return `<input class="form-control" placeholder="${this.placeholder}" />`;
}
getValue(): string {
return this.value;
}
setValue(value: string): void {
this.value = value;
console.log(`Bootstrap input value set to: ${value}`);
}
}
class BootstrapModal implements Modal {
private isVisible: boolean = false;
constructor(private title: string) {}
render(): string {
return `
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">${this.title}</div>
<div class="modal-body"></div>
</div>
</div>
</div>
`;
}
show(): void {
this.isVisible = true;
console.log(`Bootstrap modal '${this.title}' shown`);
}
hide(): void {
this.isVisible = false;
console.log(`Bootstrap modal '${this.title}' hidden`);
}
}
// Concrete Factories
class MaterialUIFactory implements UIFactory {
createButton(text: string): Button {
return new MaterialButton(text);
}
createInput(placeholder: string): Input {
return new MaterialInput(placeholder);
}
createModal(title: string): Modal {
return new MaterialModal(title);
}
}
class BootstrapUIFactory implements UIFactory {
createButton(text: string): Button {
return new BootstrapButton(text);
}
createInput(placeholder: string): Input {
return new BootstrapInput(placeholder);
}
createModal(title: string): Modal {
return new BootstrapModal(title);
}
}
// Klasa klienta używająca Factory
class Application {
private factory: UIFactory;
constructor(theme: 'material' | 'bootstrap') {
this.factory = theme === 'material'
? new MaterialUIFactory()
: new BootstrapUIFactory();
}
createLoginForm(): void {
const emailInput = this.factory.createInput('Email');
const passwordInput = this.factory.createInput('Hasło');
const loginButton = this.factory.createButton('Zaloguj');
const modal = this.factory.createModal('Logowanie');
console.log('Formularz logowania:');
console.log(emailInput.render());
console.log(passwordInput.render());
console.log(loginButton.render());
// Symulacja interakcji
emailInput.setValue('user@example.com');
passwordInput.setValue('password123');
loginButton.onClick();
modal.show();
}
}
// Użycie Abstract Factory
const materialApp = new Application('material');
materialApp.createLoginForm();
console.log('\n---\n');
const bootstrapApp = new Application('bootstrap');
bootstrapApp.createLoginForm();Observer Pattern - Reaktywne programowanie
Observer Pattern to wzorzec behawioralny, który definiuje zależność jeden-do-wielu między obiektami. Gdy stan jednego obiektu się zmienia, wszystkie zależne obiekty są automatycznie powiadamiane i aktualizowane.
Podstawowa implementacja Observer Pattern
// Klasa Subject (Observable)
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
if (typeof observer.update === 'function') {
this.observers.push(observer);
console.log('Observer został dodany');
} else {
throw new Error('Observer musi implementować metodę update()');
}
}
unsubscribe(observer) {
const index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
console.log('Observer został usunięty');
}
}
notify(data) {
console.log(`Powiadamianie ${this.observers.length} obserwatorów`);
this.observers.forEach(observer => {
observer.update(data);
});
}
}
// Konkretny Subject - Monitor giełdowy
class StockPrice extends Subject {
constructor(symbol, price) {
super();
this.symbol = symbol;
this.price = price;
this.history = [{ price, timestamp: new Date() }];
}
setPrice(newPrice) {
const oldPrice = this.price;
this.price = newPrice;
const change = newPrice - oldPrice;
const changePercent = ((change / oldPrice) * 100).toFixed(2);
const priceData = {
symbol: this.symbol,
oldPrice,
newPrice,
change,
changePercent,
timestamp: new Date()
};
this.history.push({
price: newPrice,
timestamp: priceData.timestamp
});
this.notify(priceData);
}
getPrice() {
return this.price;
}
getHistory() {
return [...this.history];
}
}
// Observery (subskrybenci)
class PriceDisplay {
constructor(name) {
this.name = name;
}
update(priceData) {
const direction = priceData.change >= 0 ? '▲' : '▼';
const changeText = priceData.change >= 0 ? '+' : '';
console.log(`[${this.name}] ${priceData.symbol}: ${priceData.newPrice} PLN ` +
`(${changeText}${priceData.change.toFixed(2)} / ${changeText}${priceData.changePercent}%) ${direction}`);
}
}
class PriceAlert {
constructor(thresholdPrice, type = 'above') {
this.thresholdPrice = thresholdPrice;
this.type = type; // 'above' lub 'below'
this.alerted = false;
}
update(priceData) {
const shouldAlert = this.type === 'above'
? priceData.newPrice >= this.thresholdPrice
: priceData.newPrice <= this.thresholdPrice;
if (shouldAlert && !this.alerted) {
console.log(`ALERT: ${priceData.symbol} ${this.type === 'above' ? 'przekroczył' : 'spadł poniżej'} ` +
`${this.thresholdPrice} PLN (aktualna cena: ${priceData.newPrice} PLN)`);
this.alerted = true;
} else if (!shouldAlert) {
this.alerted = false;
}
}
}
class PortfolioTracker {
constructor(shares) {
this.shares = shares;
this.initialValue = null;
}
update(priceData) {
const currentValue = priceData.newPrice * this.shares;
if (this.initialValue === null) {
this.initialValue = priceData.oldPrice * this.shares;
}
const profit = currentValue - this.initialValue;
const profitPercent = ((profit / this.initialValue) * 100).toFixed(2);
console.log(`Portfolio: ${this.shares} akcji ${priceData.symbol} = ${currentValue.toFixed(2)} PLN ` +
`(zysk/strata: ${profit.toFixed(2)} PLN / ${profitPercent}%)`);
}
}
// Użycie Observer Pattern
const teslaStock = new StockPrice('TSLA', 250.00);
// Tworzenie obserwatorów
const mainDisplay = new PriceDisplay('Główny ekran');
const mobileApp = new PriceDisplay('Aplikacja mobilna');
const highPriceAlert = new PriceAlert(260, 'above');
const lowPriceAlert = new PriceAlert(240, 'below');
const myPortfolio = new PortfolioTracker(10);
// Subskrypcja obserwatorów
teslaStock.subscribe(mainDisplay);
teslaStock.subscribe(mobileApp);
teslaStock.subscribe(highPriceAlert);
teslaStock.subscribe(lowPriceAlert);
teslaStock.subscribe(myPortfolio);
// Symulacja zmian cen
console.log('=== Symulacja zmian cen akcji TSLA ===\n');
teslaStock.setPrice(255.75);
console.log('');
teslaStock.setPrice(262.30);
console.log('');
teslaStock.setPrice(245.20);
console.log('');
teslaStock.setPrice(235.80);Observer Pattern z Event Emitter
// TypeScript implementacja z Event Emitter
interface EventListener<T = any> {
(data: T): void;
}
class EventEmitter<T extends Record<string, any> = Record<string, any>> {
private listeners: Map<keyof T, Set<EventListener<any>>> = new Map();
on<K extends keyof T>(event: K, listener: EventListener<T[K]>): () => void {
if (!this.listeners.has(event)) {
this.listeners.set(event, new Set());
}
this.listeners.get(event)!.add(listener);
// Zwracamy funkcję do unsubscribe
return () => this.off(event, listener);
}
off<K extends keyof T>(event: K, listener: EventListener<T[K]>): void {
const eventListeners = this.listeners.get(event);
if (eventListeners) {
eventListeners.delete(listener);
if (eventListeners.size === 0) {
this.listeners.delete(event);
}
}
}
emit<K extends keyof T>(event: K, data: T[K]): void {
const eventListeners = this.listeners.get(event);
if (eventListeners) {
eventListeners.forEach(listener => {
try {
listener(data);
} catch (error) {
console.error(`Error in event listener for ${String(event)}:`, error);
}
});
}
}
once<K extends keyof T>(event: K, listener: EventListener<T[K]>): void {
const onceListener = (data: T[K]) => {
listener(data);
this.off(event, onceListener);
};
this.on(event, onceListener);
}
removeAllListeners<K extends keyof T>(event?: K): void {
if (event) {
this.listeners.delete(event);
} else {
this.listeners.clear();
}
}
listenerCount<K extends keyof T>(event: K): number {
const eventListeners = this.listeners.get(event);
return eventListeners ? eventListeners.size : 0;
}
}
// Definicja typów eventów
interface UserEvents {
login: { userId: string; email: string; timestamp: Date };
logout: { userId: string; timestamp: Date };
profileUpdate: { userId: string; changes: Record<string, any> };
passwordChange: { userId: string; timestamp: Date };
}
// Przykład użycia z TypeScript
class UserService extends EventEmitter<UserEvents> {
private users: Map<string, any> = new Map();
login(email: string, password: string): boolean {
// Symulacja logowania
const userId = 'user_' + Math.random().toString(36).slice(2, 11);
this.users.set(userId, {
id: userId,
email,
lastLogin: new Date()
});
this.emit('login', {
userId,
email,
timestamp: new Date()
});
return true;
}
logout(userId: string): void {
if (this.users.has(userId)) {
this.emit('logout', {
userId,
timestamp: new Date()
});
this.users.delete(userId);
}
}
updateProfile(userId: string, changes: Record<string, any>): void {
if (this.users.has(userId)) {
const user = this.users.get(userId);
const updatedUser = { ...user, ...changes };
this.users.set(userId, updatedUser);
this.emit('profileUpdate', {
userId,
changes
});
}
}
changePassword(userId: string, newPassword: string): void {
if (this.users.has(userId)) {
// Symulacja zmiany hasła
this.emit('passwordChange', {
userId,
timestamp: new Date()
});
}
}
}
// Użycie
const userService = new UserService();
// Nasłuchiwanie eventów
const unsubscribeLogin = userService.on('login', (data) => {
console.log(`Użytkownik ${data.email} zalogował się o ${data.timestamp.toLocaleTimeString()}`);
});
userService.on('logout', (data) => {
console.log(`Użytkownik ${data.userId} wylogował się o ${data.timestamp.toLocaleTimeString()}`);
});
userService.on('profileUpdate', (data) => {
console.log(`Użytkownik ${data.userId} zaktualizował profil:`, data.changes);
});
userService.once('passwordChange', (data) => {
console.log(`Hasło zostało zmienione dla użytkownika ${data.userId}`);
});
// Testowanie
console.log('=== Test User Service Events ===\n');
const success = userService.login('jan@example.com', 'password123');
if (success) {
const userId = Array.from(userService['users'].keys())[0];
setTimeout(() => {
userService.updateProfile(userId, {
name: 'Jan Kowalski',
age: 30
});
}, 1000);
setTimeout(() => {
userService.changePassword(userId, 'newPassword456');
}, 2000);
setTimeout(() => {
userService.logout(userId);
}, 3000);
}Porównanie wzorców i najlepsze praktyki
Kiedy używać którego wzorca?
Module Pattern / Revealing Module Pattern:
- Stosuj, gdy potrzebujesz enkapsulacji i prywatności
- Stosuj do tworzenia singletonów
- Stosuj do organizacji kodu w przestrzenie nazw
- Unikaj, gdy potrzebujesz wielu instancji
- Unikaj, gdy potrzebujesz dziedziczenia
Factory Pattern:
- Stosuj, gdy typ obiektu jest określany w runtime
- Stosuj do unifikacji procesu tworzenia obiektów
- Stosuj, gdy masz wiele podobnych klas
- Unikaj, gdy masz tylko jedną klasę do tworzenia
- Unikaj przy prostych obiektach
Observer Pattern:
- Stosuj w programowaniu reaktywnym
- Stosuj, gdy zmiany w jednym obiekcie wpływają na wiele innych
- Stosuj w architekturze sterowanej zdarzeniami (event-driven)
- Unikaj przy prostych, bezpośrednich relacjach
- Unikaj, gdy nadawca czeka na wynik od odbiorcy: wtedy wystarczy zwykłe wywołanie metody
Łączenie wzorców w praktyce
Na koniec przykład, w którym trzy wzorce współpracują: Module Pattern ukrywa stan, statyczna metoda tworzy powiadomienia, a Observer rozsyła je subskrybentom.
// Przykład łączenia wzorców w praktycznej aplikacji
interface NotificationData {
message: string;
type: 'info' | 'warning' | 'error' | 'success';
timestamp: Date;
}
// Singleton z Module Pattern + Observer Pattern
const NotificationSystem = (function() {
// Prywatne zmienne
let instance: NotificationSystem | null = null;
let notifications: NotificationData[] = [];
let observers: Array<(notification: NotificationData) => void> = [];
class NotificationSystem {
// Statyczna metoda fabrykująca (prosta fabryka, nie wzorzec Factory Method)
static createNotification(message: string, type: NotificationData['type']): NotificationData {
return {
message,
type,
timestamp: new Date()
};
}
addNotification(message: string, type: NotificationData['type']): void {
const notification = NotificationSystem.createNotification(message, type);
notifications.push(notification);
this.notifyObservers(notification);
}
// Observer Pattern methods
subscribe(callback: (notification: NotificationData) => void): () => void {
observers.push(callback);
return () => {
const index = observers.indexOf(callback);
if (index > -1) {
observers.splice(index, 1);
}
};
}
private notifyObservers(notification: NotificationData): void {
observers.forEach(observer => observer(notification));
}
getNotifications(): NotificationData[] {
return [...notifications];
}
clearNotifications(): void {
notifications = [];
}
}
// Singleton implementation
return {
getInstance(): NotificationSystem {
if (!instance) {
instance = new NotificationSystem();
}
return instance;
}
};
})();
// Użycie połączonych wzorców
const notificationService = NotificationSystem.getInstance();
// Subskrybenci (Observer Pattern)
const unsubscribe1 = notificationService.subscribe((notification) => {
console.log(`[UI] ${notification.type.toUpperCase()}: ${notification.message}`);
});
const unsubscribe2 = notificationService.subscribe((notification) => {
if (notification.type === 'error') {
console.log(`[LOG] Error logged: ${notification.message} at ${notification.timestamp}`);
}
});
// Testowanie
notificationService.addNotification('Witaj w aplikacji!', 'info');
notificationService.addNotification('Ostrzeżenie: mało miejsca na dysku', 'warning');
notificationService.addNotification('Błąd połączenia z serwerem', 'error');
notificationService.addNotification('Dane zostały zapisane pomyślnie', 'success');Podsumowanie
Wzorce projektowe Module, Factory i Observer to fundamenty nowoczesnego programowania JavaScript/TypeScript:
- Module Pattern zapewnia enkapsulację i organizację kodu
- Revealing Module Pattern poprawia czytelność przez jasne definiowanie publicznego API
- Factory Pattern ukrywa szczegóły tworzenia obiektów
- Observer Pattern umożliwia reaktywne programowanie i luźne powiązanie
Podobnie jak starożytni budowniczowie używali sprawdzonych wzorców architektonicznych, współcześni programiści wykorzystują te wzorce projektowe do tworzenia solidnych, skalowalnych aplikacji. Znajomość tych wzorców jest kluczowa dla każdego programisty JavaScript/TypeScript.
Kod do tej lekcji: index.js
// Wzorzec Module - System zarządzania Parkiem
// Ćwiczenie: Zaimplementuj klasę ParkCore z systemem modułów
class ParkCore {
constructor(name) {
this.name = name;
this.modules = new Map();
this.isRunning = false;
}
// Zaimplementuj metody:
// registerModule(name, module) - rejestruje moduł
// getModule(name) - zwraca moduł
// start() - uruchamia wszystkie moduły
registerModule(name, module) {
// Twój kod tutaj
}
getModule(name) {
// Twój kod tutaj
}
start() {
// Twój kod tutaj
}
}
const park = new ParkCore("Jurassic Park");
console.log("Park:", park.name);Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Który wzorzec projektowy jest najlepszy dla zapewnienia, że istnieje tylko jedna instancja systemu bezpieczeństwa?