javascript / PHP [Design Patterns - Facade Pattern]
This pattern involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes.
/** * Design Patterns - Facade Pattern * https://www.tutorialspoint.com/design_pattern/facade_pattern.htm */ // interface function Shape() {} Shape.prototype.draw = function() {throw "Shape::draw() must be overridden";}; // implements Shape function Rectangle() { Shape.call(this); } Rectangle.prototype = new Shape(); Rectangle.prototype.draw = function() { console.log("Rectangle::draw()"); }; // implements Shape function Square() { Shape.call(this); } Square.prototype = new Shape(); Square.prototype.draw = function() { console.log("Square::draw()"); }; // implements shape function Circle() { Shape.call(this); } Circle.prototype = new Shape(); Circle.prototype.draw = function() { console.log("Circle::draw()"); }; function ShapeMaker() { this.circle = new Circle(); this.rectangle = new Rectangle(); this.square = new Square(); } ShapeMaker.prototype.drawCircle = function() { this.circle.draw(); }; ShapeMaker.prototype.drawRectangle = function() { this.rectangle.draw(); }; ShapeMaker.prototype.drawSquare = function() { this.square.draw(); }; function FacadePatternDemo() { this.shapeMaker = new ShapeMaker(); } FacadePatternDemo.prototype.main = function() { this.shapeMaker.drawCircle(); this.shapeMaker.drawRectangle(); this.shapeMaker.drawSquare(); }; var demo = new FacadePatternDemo(); demo.main();
Output:
Circle::draw()
Rectangle::draw()
Square::draw()
<?php /** * The complicated, underlying logic. */ class CPU { public function freeze() { echo 'CPU freeze'.PHP_EOL; } public function jump($position) { printf("CPU jumping to 0x%x %s", $position, PHP_EOL); } public function execute() { echo 'CPU executing...'.PHP_EOL; } } class Memory { public function load($position, $data) { printf("Loading position 0x%x from memory, \"%s\"%s", $position, implode('', $data), PHP_EOL); } } class HardDrive { public function read($lba, $size) { printf("HardDrive is reading sector#%d, size=%d %s", $lba, $size, PHP_EOL); return ['H','e','l','l','o']; } } /** * The facade that users would be interacting with. */ class ComputerFacade { protected $cpu; protected $memory; protected $hd; public function __construct() { $this->cpu = new CPU; $this->ram = new Memory; $this->hd = new HardDrive; } public function start() { $this->cpu->freeze(); $this->ram->load(0x8280, $this->hd->read(0, 512)); $this->cpu->jump(0x8280); $this->cpu->execute(); } } /** * How a user could start the computer. */ $computer = new ComputerFacade; $computer->start();
OUTPUT:
CPU freeze
HardDrive is reading sector#0, size=512
Loading position 0x8280 from memory, "Hello"
CPU jumping to 0x8280
CPU executing...