I'm wondering what's the difference between these two patterns.
I may be mistaken but they seem to be using the same structure to achieve a higher-level interface to a larger body of code.
Facade Pattern:
var mobileEvent = {
// ...
stop: function (e) {
e.preventDefault();
e.stopPropagation();
}
// ...
};
Object Literal:
var myObject = {
property1:"something",
property2:"something else",
method1:function(){
console.log('hello world');
}
};
If they really serve different purposes, when should I use them exactly?
Just the fact that they use the same syntax does not mean they have same purpose. Many design patterns have exactly the same implementation but have different meaning based on the context.
Facade encapsulates one or more objects and provides easier API for the client, hiding the obscurities and making it harder to make a mistake. In your example mobileEvent.stop() function encapsulates two JavaScript calls that have to go together in order to achieve some higher level behaviour.
Object literal isn't really a pattern, it is just a way to define one-time object in JavaScript. As you can see it can be used to implement Facade pattern and many others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With