Please enable JavaScript.
Coggle requires JavaScript to display documents.
W10 - JS Patterns [Part 2] [28/64 IMPOrtant] (Design Patterns (Singleton…
W10 - JS Patterns [Part 2] [28/64 IMPOrtant]
Prototypes in JS
Think of it as
a customisable object
that can be used as
a starting point
to
build out other objects
All objects built using prototype
reference common properties and methods
shared by reference
rather than duplication
example
function Arrangement(name, vase, quality = 1){
. this.name = name;
. this.vase = vase;
. this.quality = quality;
}
Arrangement.prototype.type = 'floral';
Arrangement.prototype.storage = 'cool';
Arrangement.prototype.logItem = function( ){ };
Prototype Chaining
JS allows
base one prototype on another
inherits keys and values from another
Design Patterns
Singleton Pattern
Only one instance of class can exist
If
no instance
of class exists
new
is created, else
reference to existing instance
returned
Intent
: Ensure class has
only one instance
and
prvode a global point of access
to it.
example
class Singleton {
.
constructor( ) {
. .
if (!Singleton.instance) {
. . .
Singletom.instance = new Logger ( );
. .
}
.
}
.
getInstance( ) {
. .
return Singleton.instance;
.
}
}
Factory Pattern
Intent
: Define
an interface for creating an object
but let
subclasses
decide which
class to instantiate
example
Builder Pattern
use when you want to
customise instance of objects
that you will create
Intent
:
Separate
construction of
complex
object from
its representation
so that same construction process can create
different representations
Structural - Adapter Pattern
Intent
: Convert interface of a class into another clients expect, Lets classes work together that couldn't because of
incompatible interfaces
Decorator Pattern
Intent
: Attach
additional responsibilities
to an object dynamically. Decorators provide a
flexible alt to subclassing for extending functionality
Behavioural - Chain of Responsibility
Command Pattern