Wzorce projektowe Flashcards
Wzorzec kontrukcyjny Simple Factory
function SimpleFactory(type,arr1,arr2){
switch(type){
case “type1” :
return {type: type, arr1: arr1, arr2: arr2}
case “type2” :
return {type: type, arr1: arr1, arr2: arr2}
}
}
let obj1 = SimpleFactory("type1","arr1","arr2"); let obj2 = SimpleFactory("type2","arr1","arr2"); console.log(obj1); console.log(obj2);
Wzorzec konstrukcyjny Builder
function Builder() {
this.arr1 = “”;
this.arr2 = “”;
this.setArr1 = function(arr1){ this.arr1 = arr1; return this; } this.setArr2 = function(arr2){ this.arr2 = arr2; return this; } this.build = function(){ return{ arr1: this.arr1, arr2: this.arr2 }; }; }
const user1 = new Builder().setArr1(“arr1”).setArr2(“arr2”).build();
console.log(user1);
Wzorzec konstrukcyjny Abstract Factory
function Funkcja1(arr1,arr2){
this.arr1 = arr1;
this.arr2 = arr2;
}
function Funkcja2(arr1,arr2){
this.arr1 = arr1;
this.arr2 = arr2;
}
function Funkcja11(arr1,arr2){ this.arr1 = arr1; this.arr2 = arr2 } function Funkcja22(arr1,arr2){ this.arr1 = arr1; this.arr2 = arr2 } function AbstractFactory(type){ if(type === "funkcja1lub2"){ return { Funkcja1: function(arr1,arr2){ return new Funkcja1(arr1,arr2); }, Funkcja2: function(arr1,arr2){ return new Funkcja2(arr1,arr2); } } } else if(type === "funkcja11lub22"){ return{ Funkcja11: function(arr1,arr2){ return new Funkcja11(arr1,arr2); }, Funkcja22: function(arr1,arr2){ return new Funkcja22(arr1,arr2); } } } } const f1lub2 = AbstractFactory("funkcja1lub2"); const f11lub22 = AbstractFactory("funkcja11lub22"); const f1 = f1lub2.Funkcja1("arr1","arr2"); const f2 = f1lub2.Funkcja2("arr1","arr2"); const f11 = f11lub22.Funkcja11("arr1","arr2"); const f22 = f11lub22.Funkcja22("arr1","arr2"); console.log(f1); console.log(f2); console.log(f11); console.log(f22);
Wzorzec konstrukcyjny Factory Method
function Funkcja1(arr1,arr2){
this.arr1 = arr1;
this.arr2 = arr2;
}
function Funkcja2(arr1,arr2){
this.arr1 = arr1;
this.arr2 = arr2;
}
function FactoryMethod(){
this.createObject = function(type,arr1,arr2){
switch(type){
case “type1”:
return new Funkcja1(arr1,arr2);
break;
case “type2”:
return new Funkcja2(arr1,arr2);
break;
}
}
}
const factory = new FactoryMethod();
let obj1 = factory.createObject(“type1”,”arr1”,”arr2”);
let obj2 = factory.createObject(“type2”,”arr1”,”arr2”);
console.log(obj1);
console.log(obj2);
Wzorzec konstrukcyjny Singleton
function Singleton() { let lang = ""; // Prywatna zmienna if (Singleton.instance) { return Singleton.instance; // Jeśli instancja już istnieje, zwróć ją } // Publiczne metody this.setLang = function(newLang) { lang = newLang; }; this.getLang = function() { return lang; }; Singleton.instance = this; // Przechowujemy jedną instancję }
Wzorzec factory with composition
// Silniki
function ElectricEngine(arr1, arr2) {
this.arr1 = arr1;
this.arr2 = arr2;
this.getType = function() {
return “Electric Engine”;
};
}
function CombustionEngine(arr1, arr2) {
this.arr1 = arr1;
this.arr2 = arr2;
this.getType = function() {
return “Combustion Engine”;
};
}
// Skrzynie biegów
function ManualTransmission(arr1, arr2) {
this.arr1 = arr1;
this.arr2 = arr2;
this.getType = function() {
return “Manual Transmission”;
};
}
function AutomaticTransmission(arr1, arr2) {
this.arr1 = arr1;
this.arr2 = arr2;
this.getType = function() {
return “Automatic Transmission”;
};
}
// Fabryki komponentów (komponenty samochodu)
function EngineFactory(type, arr1, arr2) {
if (type === “electric”) {
return new ElectricEngine(arr1, arr2);
} else if (type === “combustion”) {
return new CombustionEngine(arr1, arr2);
} else {
throw new Error(“Unknown engine type”);
}
}
function TransmissionFactory(type, arr1, arr2) {
if (type === “manual”) {
return new ManualTransmission(arr1, arr2);
} else if (type === “automatic”) {
return new AutomaticTransmission(arr1, arr2);
} else {
throw new Error(“Unknown transmission type”);
}
}
// Komponent samochód
function Car(engine, transmission) {
this.engine = engine;
this.transmission = transmission;
this.describe = function() {
return This car has a ${this.engine.getType()} and a ${this.transmission.getType()}.
;
};
}
// Fabryka samochodów
function CarFactory(engineType, transmissionType, engineArr1, engineArr2, transArr1, transArr2) {
const engine = EngineFactory(engineType, engineArr1, engineArr2);
const transmission = TransmissionFactory(transmissionType, transArr1, transArr2);
return new Car(engine, transmission);
}
// Przykładowe użycie
const electricCar = CarFactory(“electric”, “automatic”, [1, 2], [3, 4], [5, 6], [7, 8]);
console.log(electricCar.describe()); // This car has a Electric Engine and a Automatic Transmission.
const combustionCar = CarFactory(“combustion”, “manual”, [10, 20], [30, 40], [50, 60], [70, 80]);
console.log(combustionCar.describe()); // This car has a Combustion Engine and a Manual Transmission.
Wzorzec strukturalny Fasada
// Złożone systemy jako funkcje
function processPayment(amount) {
console.log(Processing payment of \$\${amount}
);
}
function checkInventory(item) {
console.log(Checking inventory for item: ${item}
);
}
function arrangeShipping(address) {
console.log(Arranging shipping to ${address}
);
}
function sendNotification(message) {
console.log(Sending notification: ${message}
);
}
// Fasada jako funkcja
function completePurchase(item, amount, address) {
console.log(“Starting purchase process…”);
checkInventory(item); // Sprawdzanie stanu magazynu
processPayment(amount); // Przetwarzanie płatności
arrangeShipping(address); // Organizowanie wysyłki
sendNotification(“Your purchase is complete!”); // Wysyłanie powiadomienia
}
// Użycie fasady
completePurchase(“Laptop”, 1500, “123 Main St.”);
Wzorzec strukturalny Adapter
// Standardowy interfejs w systemie
function Car(make, model) {
this.make = make;
this.model = model;
}
Car.prototype.startEngine = function () {
return Starting the engine of ${this.make} ${this.model}.
;
};
// Zewnętrzna klasa, która działa inaczej
function Bike(brand, type) {
this.brand = brand;
this.type = type;
}
Bike.prototype.pedal = function () {
return Pedaling the ${this.type} bike by ${this.brand}.
;
};
// Adapter dla klasy Bike
function BikeAdapter(bike) {
this.make = bike.brand; // Tłumaczymy brand na make
this.model = bike.type; // Tłumaczymy type na model
}
BikeAdapter.prototype.startEngine = function () {
return this.make
? Simulating engine start for ${this.make} ${this.model}.
: This bike does not have an engine!
;
};
// Istniejący samochód
const car = new Car(“Toyota”, “Corolla”);
console.log(car.startEngine()); // Starting the engine of Toyota Corolla.
// Zewnętrzny rower
const bike = new Bike(“Trek”, “Mountain Bike”);
console.log(bike.pedal()); // Pedaling the Mountain Bike bike by Trek.
// Użycie adaptera
const adaptedBike = new BikeAdapter(bike);
console.log(adaptedBike.startEngine());
// Simulating engine start for Trek Mountain Bike.
Wzorzec strukturalny Decorator
// Podstawowa kawa
function Coffee() {
this.cost = 5; // Koszt podstawowej kawy
this.getDescription = function() {
return “Coffee”;
};
}
// Dekorator - dodanie mleka do kawy
function MilkDecorator(coffee) {
this.coffee = coffee; // Przechowywanie obiektu Coffee
this.cost = coffee.cost + 1; // Koszt mleka
this.getDescription = function() {
return coffee.getDescription() + “ + Milk”; // Opis z mlekiem
};
}
// Dekorator - dodanie cukru do kawy
function SugarDecorator(coffee) {
this.coffee = coffee; // Przechowywanie obiektu Coffee
this.cost = coffee.cost + 0.5; // Koszt cukru
this.getDescription = function() {
return coffee.getDescription() + “ + Sugar”; // Opis z cukrem
};
}
// Użycie
let myCoffee = new Coffee();
console.log(myCoffee.getDescription() + “ costs “ + myCoffee.cost); // Coffee costs 5
// Dekorowanie kawy poprzez dodanie mleka
myCoffee = new MilkDecorator(myCoffee);
console.log(myCoffee.getDescription() + “ costs “ + myCoffee.cost); // Coffee + Milk costs 6
// Dekorowanie kawy poprzez dodanie cukru
myCoffee = new SugarDecorator(myCoffee);
console.log(myCoffee.getDescription() + “ costs “ + myCoffee.cost); // Coffee + Milk + Sugar costs 6.5
Wzorzec strukturalny FlyWeight
// Fabryka Flyweight
function TreeFactory() {
const treeTypes = {}; // Przechowuje już utworzone typy drzew
return { getTreeType: function (name, color, texture) { const key = `${name}-${color}-${texture}`; if (!treeTypes[key]) { treeTypes[key] = createTreeType(name, color, texture); } return treeTypes[key]; } }; function createTreeType(name, color, texture) { return { name, color, texture }; // Typ drzewa jako obiekt współdzielony } }
// Funkcja rysująca drzewo
function drawTree(treeType, x, y) {
console.log(Rysowanie drzewa: ${treeType.name} (${treeType.color}, ${treeType.texture}) na współrzędnych (${x}, ${y}).
);
}
// Korzystanie z Flyweight
// Inicjalizacja fabryki
const treeFactory = TreeFactory();
// Uzyskanie współdzielonych typów drzew
const oakTreeType = treeFactory.getTreeType(‘Dąb’, ‘Zielony’, ‘Chropowata’);
const pineTreeType = treeFactory.getTreeType(‘Sosna’, ‘Zielony’, ‘Gładka’);
const reusedOakTreeType = treeFactory.getTreeType(‘Dąb’, ‘Zielony’, ‘Chropowata’); // Ten sam obiekt co oakTreeType
// Sprawdzenie, czy obiekty są współdzielone
console.log(oakTreeType === reusedOakTreeType); // true
// Rysowanie drzew
drawTree(oakTreeType, 10, 20); // Rysowanie drzewa Dąb na współrzędnych (10, 20)
drawTree(pineTreeType, 50, 100); // Rysowanie drzewa Sosna na współrzędnych (50, 100)
drawTree(reusedOakTreeType, 30, 40); // Rysowanie współdzielonego Dębu na innych współrzędnych (30, 40)
Wzorzec Behawioralny mediator
// Mediator: zarządza całą komunikacją
function ChatMediator() {
this.users = []; // Lista użytkowników w czacie
// Rejestracja użytkownika w czacie this.addUser = function (user) { this.users.push(user); user.setMediator(this); // Ustawiamy czat jako mediatora użytkownika }; // Wysyłanie wiadomości od jednego użytkownika do innych this.sendMessage = function (message, sender) { this.users.forEach(user => { if (user !== sender) { // Wiadomość nie wraca do nadawcy user.receiveMessage(message, sender.name); } }); }; }
// Użytkownik: osoba w czacie
function User(name) {
this.name = name;
this.mediator = null;
// Ustawienie mediatora (czatu) dla użytkownika this.setMediator = function (mediator) { this.mediator = mediator; }; // Wysyłanie wiadomości przez mediatora this.sendMessage = function (message) { console.log(`${this.name} wysyła: "${message}"`); this.mediator.sendMessage(message, this); }; // Otrzymywanie wiadomości od mediatora this.receiveMessage = function (message, senderName) { console.log(`${this.name} otrzymuje: "${message}" od ${senderName}`); }; }
// Przykład działania
document.addEventListener(“DOMContentLoaded”, () => {
const chat = new ChatMediator(); // Tworzymy czat (mediator)
const alice = new User("Alicja"); const bob = new User("Bob"); const charlie = new User("Charlie"); chat.addUser(alice); chat.addUser(bob); chat.addUser(charlie); alice.sendMessage("Cześć wszystkim!"); // Wiadomość Alicji bob.sendMessage("Hej Alicja!"); // Wiadomość Boba charlie.sendMessage("Cześć! Co słychać?"); // Wiadomość Charliego });