ypatterns
Miscellaneous programming patterns.
Gate
This is the pattern of usage counter.
Anybody can enter the gate is the gate is not closed.
When gate is closed, nobody allowed entering. However, all those that are already inside, can exit the gate.
The completion of gate closure will be called when everybody left (exited the gate).
Usage
var gate = require('ypatterns').gate;
if (gate.enter()) {
gate.exit();
}
else {
}
...
gate.close(function() {
});
Handle Wrapper
This pattern is for objects that exhibit handle-like facade. Upon instantiation, such objects return handle, which has
only method close
. Such facade is useful for object that are listeners and call for notifications.
To expose handle facade, one has to implement factory, which has initialize
and cleanup
methods.
The wrapper takes care to call cleanup only after initialization is completed.
Definition
var handleWrapper = require('ypatterns').handleWrapper;
function factory(...) {
function initialize(callback) {
}
function cleanup(callback) {
}
return handleWrapper({ initialize: initialize, cleanup: cleanup });
}
Usage
var handle = factory(...);
...
handle.close(function() {
});
Sync-Async Facade
This pattern is used to create objects which expose asynchronous instantiation, but can be used synchronously. Better
behaving usage will use object upon instantiation completion, which ensures asynchronous initialization was completed.
However, if object is used before completion, this will still work. The facade wrapper invoke synchronous initializer
if object is used before asynchronous initializer was completed. All this done in a way opaque to usage.
Usage
var obj = factory(..., function() {
obj.foo();
});
obj.foo();
Definition
var syncasyncFacade = require('ypatterns').syncasyncFacade;
function factory(..., callback) {
function createInstance() {
return instance;
}
function initializeAsync(instance, callback) {
}
function initializeSync(instance) {
}
return syncasyncFacade({
create: createInstance,
initializeAsync: initializeAsync,
initializeSync: initializeSync
},
callback);
}
License
MIT