In questo codice informatico da me preparato in ES5, NON VOGLIO PROGRAMMARE IN ES6, var CONFIG = {
ORDER_SIDE: 'BID',
SIZE: 1,
MAX_OPERATIONS: 3,
LEVELS: { BID: 6, ASK: 6 },
SECONDS: 5,
TICK: 1,
MONITORING_MODE: 'MONITORA_yourlevel'
};
var separator = "---------------------------------------------------\r\n";
var lastBidPrice, lastBidQuantity, lastAskPrice, lastAskQuantity;
var BookStateManager = (function() {
var cachedBookState = null;
var UserContext = {};
code
return {
getBookState: function(book) {
var newState = this.createBookState(book);
if (this.hasBookStateChanged(newState)) {
cachedBookState = newState;
StateManager.updateLastValues(newState);
}
return cachedBookState;
},
hasBookStateChanged: function(newState) {
if (!cachedBookState) return true;
var sides = ['BID', 'ASK'];
for (var i = 0; i < sides.length; i++) {
if (this.isSideChanged(sides[i], newState)) {
return true;
}
}
return false;
},
isSideChanged: function(side, newState) {
var maxLevel = CONFIG.LEVELS[side];
var cachedPrices = cachedBookState.book[side].Prices;
var cachedQuantities = cachedBookState.book[side].Quantities;
var newPrices = newState.book[side].Prices;
var newQuantities = newState.book[side].Quantities;
for (var level = 0; level <= maxLevel; level++) {
if (cachedPrices[level] !== newPrices[level] ||
cachedQuantities[level] !== newQuantities[level]) {
return true;
}
}
return false;
},
createBookState: function(book) {
var state = { book: book };
var combinations = [
{ side: 'BID', type: 'Price' },
{ side: 'BID', type: 'Quantity' },
{ side: 'ASK', type: 'Price' },
{ side: 'ASK', type: 'Quantity' }
];
Assistant
code
for (var i = 0; i < combinations.length; i++) {
var combo = combinations[i];
var key = combo.side.toLowerCase() + combo.type;
state[key] = this.getData(book, combo.side, CONFIG.LEVELS[combo.side], combo.type);
}
return state;
function collectBookLogParts(book) {
var logParts = ["BID:\n"];
addLevels(logParts, 'BID', book);
logParts.push(separator, "ASK:\n");
addLevels(logParts, 'ASK', book);
var tick = calculateTick(book.BID.Prices, book.ASK.Prices);
return logParts;
}
function logFullBook() {
var book = UserContext.book;
var logParts = collectBookLogParts(book);
logger.log('message', { message: logParts.join('') }, false); // Utilizza logger invece di Log
}
function priceUpdate(side, book, status) {
var prices = UserContext.prices[side];
var targetPriceLevel = UserContext.targetPriceLevels[side];
var targetPrice = book[side].Prices[targetPriceLevel];
var oldPrice = prices.oldLevel;
code
if (targetPrice === oldPrice) return;
var newOrder = OrderUtils.processOrModOrder(side, ps, targetPrice);
if (!newOrder) return;
prices.current = targetPrice;
var direction = Helper.priceDirection(targetPrice, oldPrice);
var levelDifference = (direction === 1) ? (CONFIG.LEVELS[side] + 1) :
(direction === -1) ? (CONFIG.LEVELS[side] - 1) :
CONFIG.LEVELS[side];
logger.log('LevelChange', { lastLevel: levelDifference, priceLevel: targetPriceLevel }, true);
status.secondCount = 0;
status.numOperazione++;
}
function checkOps() {
var status = UserContext.status;
if (status.numOperazione < CONFIG.MAX_OPERATIONS) {
return false;
}
function onPriceEvent(ctx) {
var price = Val(ps, "LAST");
if (ctx.lastPrice === price) return;
logger.log('PriceChange', {
previousPrice: ctx.lastPrice,
currentPrice: price,
currentTime: Now().ToString("HH:mm:ss.ff")
});
ctx.lastPrice = price;
}
function onTimeEvent(ctx) {
ctx.status.secondCount++;
manageCycle();
}
function handleEvent(context, type) {
if (type === TSEventType.Price) {
onPriceEvent(context);
} else if (type === TSEventType.Time) {
onTimeEvent(context);
}
}
function marketEvent(Book, mapBookData, handleEvent, UserContext, SystemContext) {
return function() {
if (!UserContext.status.run) return;
var originalBook = Book(ps);
var mappedBook = mapBookData(originalBook);
UserContext.book = mappedBook;
handleEvent(UserContext, SystemContext.EventType);
};
}
if (SystemContext.IsFirst) {
setupTradeContext();
}
var marketEventInstance = marketEvent(Book, mapBookData, handleEvent, UserContext, SystemContext);
marketEventInstance(); Per migliorare l'aderenza all'OPEN CLOSE PRINCIPLE, mi consigli di usare dei Pattern Factory per Incapsula la creazione di oggetti complessi, consentendo di estendere il comportamento senza modificare i moduli esistenti ?
Sì, utilizzare i Pattern Factory per incapsulare la creazione di oggetti complessi è un'ottima strategia per migliorare l'aderenza al Principio Open/Closed (OCP) nel tuo codice ES5. Il Principio Open/Closed sostiene che le entità software (classi, moduli, funzioni, ecc.) dovrebbero essere aperte all'estensione ma chiuse alla modifica. Implementando pattern Factory, puoi estendere il comportamento del tuo sistema senza dover modificare i moduli esistenti, migliorando così la manutenibilità e la scalabilità del tuo codice.
Benefici dell'uso del Pattern Factory per OCP
Incapsulamento della Creazione degli Oggetti: Centralizzando la logica di creazione, riduci la dipendenza tra i componenti e semplifichi le modifiche future.
Facilità di Estensione: Aggiungere nuovi tipi di oggetti o modificare il processo di creazione senza alterare il codice esistente.
Migliore Gestione delle Dipendenze: Riduci l'accoppiamento tra i moduli, rendendo il codice più modulare e testabile.
Implementazione del Pattern Factory nel Tuo Codice
Vediamo come puoi applicare il Pattern Factory per alcuni componenti chiave del tuo codice, come ad esempio la gestione degli ordini e il logger.
1. Factory per la Creazione degli Ordini
Puoi creare una Factory per gestire la creazione, la modifica e l'eliminazione degli ordini. Questo ti permette di aggiungere nuovi tipi di ordini senza modificare direttamente OrderUtils.
Analogamente, puoi creare una Factory per generare istanze di logger o per gestire diversi tipi di log.
javascript
// LoggerFactory.js
var LoggerFactory = (function() {
return {
createLogger: function(type) {
// Potresti estendere questa funzione per creare diversi tipi di logger
return logger; // Restituisce l'istanza esistente, ma può essere estesa
}
};
})();
4. Refactoring del Logger per Usare la LoggerFactory
javascript
var logger = (function() {
// Definisci il logger come prima
return {
// ... metodi del logger ...
};
})();
var Logger = LoggerFactory.createLogger('default');
// Uso del logger
Logger.log('Initialization Complete', {
bidPrice: UserContext.prices.BID.current,
askPrice: UserContext.prices.ASK.current
}, true);
Applicazione del Pattern Factory ad Altri Componenti
Oltre agli ordini e al logger, puoi applicare il Pattern Factory ad altri componenti complessi del tuo sistema, come ad esempio:
BookStateManager: Se prevedi di avere diverse strategie di gestione dello stato del book, una Factory può aiutare a creare istanze diverse senza modificare il manager stesso.
Gestione degli Eventi: Se hai diversi tipi di eventi da gestire, una Factory può creare gestori specifici per ciascun tipo.
Esempio: Factory per Gestione degli Eventi
javascript
// EventHandlerFactory.js
var EventHandlerFactory = (function() {
return {
getHandler: function(eventType) {
var handlers = {
'Price': onPriceEvent,
'Time': onTimeEvent
// Aggiungi altri handler qui
};
return handlers[eventType] || function() {};
}
};
})();
javascript
function handleEvent(context, type) {
var handler = EventHandlerFactory.getHandler(type);
handler(context);
}
Conclusione
Implementare i Pattern Factory nel tuo codice ES5 può significativamente migliorare la conformità al Principio Open/Closed, facilitando l'estensione delle funzionalità senza necessità di modificare il codice esistente. Questo approccio rende il sistema più flessibile, modulare e più facile da mantenere nel tempo.
Se desideri approfondire ulteriormente, considera anche l'adozione di altri pattern come il Module Pattern per organizzare meglio i tuoi componenti o il Strategy Pattern per gestire comportamenti intercambiabili.
Se hai bisogno di ulteriori dettagli o esempi specifici su come implementare questi pattern nel tuo contesto, fammelo sapere!