Facade Design Pattern in TypeScript
Facade Pattern
What is Facade pattern for? According to sourcemaking.com, there are mainly two intentions:
- Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
- Wrap a complicated subsystem with a simpler interface.
Facade in formula.ts
In formula.ts, I’d like to expose all functions directly to end users like this:
1 | const formula = requre('formula.ts'); |
Absolutely it’s not a good design to mix ~500 functions in a single lib file. In the offical documentation of Excel, functions are categorized into multiple groups:
- Compatibility functions
- Cube functions
- Database functions
- Date and time functions
- Engineering functions
- Financial functions
- Information functions
- Logical functions
- Lookup and reference functions
- Math and trigonometry functions
- Statistical functions
- Text functions
- Web function
The first idea came to me is Facade pattern, which encapsulats multiple complex subsystems with a single interface object, this is exactly what I want. Here’s an example written in TypeScript for fomula.ts:
1 | // fist subsystem DateTime |
You can run this script in TypeScript Playground, output is like this:
1 | f.ADD(1, 2) = 3 |
Mixins in TypeScript
In the above example we duplicated the functions in Formula
so as to expose an unified interface, this is inevitable. However it kind of borthers me that I had to repeat the return
statement in each of them, as matter of fact they didn’t add much value except calling a corresponding function in its subsystem. TypseScript does support a better way by using Mixins to building up classes from reusable components. Here’s an example:
1 | class CanEat { |
Here we go, with applyMixins
, you no longer need to repeat those return
s, making the final class short and concise.