Shopy 101
← Facade İndirmek için giriş yap
"},"page":{"wt":"{{{page|{{SUBPAGENAME}}}}} <!-- DO NOT MODIFY THIS LINE! -->"},"stage":{"wt":"25"},"stage date":{"wt":"29 Jan, 2014"},"stage comment":{"wt":"Add more illustrations."},"previous":{"wt":"Decorator"},"next":{"wt":"Factory method"},"content":{"wt":"A Facade pattern hides the complexities of the system and provides an interface to the client from where the client can access the system.\nDividing a system into subsystems helps reduce complexity. We need to minimize the communication and dependencies between subsystems. For this, we introduce a facade object that provides a single, simplified interface to the more general facilities of a subsystem.\n== Examples ==\nThe <code>SCP</code> command is a shortcut for SSH commands. A remote file copy could be done writing several commands with an SSH connection but it can be done in one command with <code>SCP</code>. So the <code>SCP</code> command is a facade for the SSH commands. Although it may not be coded in the object programming paradigm, it is a good illustration of the design pattern.\n== Cost ==\nThis pattern is very easy and has not additional cost.\n=== Creation ===\nThis pattern is very easy to create.\n=== Maintenance ===\nThis pattern is very easy to maintain.\n=== Removal ===\nThis pattern is very easy to remove too.\n== Advises ==\n* Do not use this pattern to mask only three or four method calls.\n== Implementations ==\n\n{{Java/Hidden begin|title=Implementation in Java}}\nThis is an abstract example of how a client (\"you\") interacts with a facade (the \"computer\") to a complex system (internal computer parts, like CPU and HardDrive).\n\n<syntaxhighlight lang=\"java\">\n/* Complex parts */\n\nclass CPU {\n public void freeze() { ... }\n public void jump(long position) { ... }\n public void execute() { ... }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"java\">\nclass Memory {\n public void load(long position, byte[] data) { ... }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"java\">\nclass HardDrive {\n public byte[] read(long lba, int size) { ... }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"java\">\n/* Facade */\n\nclass Computer {\n private CPU processor;\n private Memory ram;\n private HardDrive hd;\n\n public Computer() {\n this.processor = new CPU();\n this.ram = new Memory();\n this.hd = new HardDrive();\n }\n\n public void start() {\n processor.freeze();\n ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));\n processor.jump(BOOT_ADDRESS);\n processor.execute();\n }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"java\">\n/* Client */\n\nclass You {\n public static void main(String[] args) {\n Computer facade = new Computer();\n facade.start();\n }\n}\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in C#}}\n<syntaxhighlight lang=\"csharp\">\nusing System;\n\nnamespace Facade\n{\n\tpublic class CPU\n {\n\t\tpublic void Freeze() { }\n\t\tpublic void Jump(long addr) { }\n\t\tpublic void Execute() { }\n\t}\n\n\tpublic class Memory\n\t{\n\t\tpublic void Load(long position, byte[] data) { }\n }\n\n\tpublic class HardDrive\n\t{\n\t\tpublic byte[] Read(long lba, int size) { return null; }\n\t}\n\n\tpublic class Computer\n\t{\n\t\tvar cpu = new CPU();\n\t\tvar memory = new Memory();\n\t\tvar hardDrive = new HardDrive();\n\n\t\tpublic void StartComputer()\n\t\t{\n\t\t\tcpu.Freeze();\n\t\t\tmemory.Load(0x22, hardDrive.Read(0x66, 0x99));\n\t\t\tcpu.Jump(0x44);\n\t\t\tcpu.Execute();\n\t\t}\n\t}\n\n\tpublic class SomeClass\n\t{\n public static void Main(string[] args)\n {\n var facade = new Computer();\n facade.StartComputer();\n }\n }\n}\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in Ruby}}\n<syntaxhighlight lang=\"ruby\">\n# Complex parts\nclass CPU\n def freeze; puts 'CPU: freeze'; end\n def jump(position); puts \"CPU: jump to #{position}\"; end\n def execute; puts 'CPU: execute'; end\nend\n\nclass Memory\n def load(position, data)\n puts \"Memory: load #{data} at #{position}\"\n end\nend\n\nclass HardDrive\n def read(lba, size)\n puts \"HardDrive: read sector #{lba} (#{size} bytes)\"\n return 'hdd data'\n end\nend\n\n# Facade\nclass Computer\n BOOT_ADDRESS = 0\n BOOT_SECTOR = 0\n SECTOR_SIZE = 512\n\n def initialize\n @cpu = CPU.new\n @memory = Memory.new\n @hard_drive = HardDrive.new\n end\n\n def start_computer\n @cpu.freeze\n @memory.load(BOOT_ADDRESS, @hard_drive.read(BOOT_SECTOR, SECTOR_SIZE))\n @cpu.jump(BOOT_ADDRESS)\n @cpu.execute\n end\nend\n\n# Client\nfacade = Computer.new\nfacade.start_computer\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in Python}}\n<syntaxhighlight lang=\"python\">\n# Complex parts\nclass CPU:\n def freeze(self): pass\n def jump(self, position): pass\n def execute(self): pass\n \nclass Memory:\n def load(self, position, data): pass\n \nclass HardDrive:\n def read(self, lba, size): pass\n \n# Facade\nclass Computer:\n def __init__(self):\n self.cpu = CPU()\n self.memory = Memory()\n self.hard_drive = HardDrive()\n \n def start_computer(self):\n self.cpu.freeze()\n self.memory.load(0, self.hard_drive.read(0, 1024))\n self.cpu.jump(10)\n self.cpu.execute()\n \n# Client\nif __name__ == '__main__':\n facade = Computer()\n facade.start_computer()\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in PHP}}\n<syntaxhighlight lang=\"php\">\n/* Complex parts */\nclass CPU\n{\n public function freeze() { /* ... */ }\n public function jump( $position ) { /* ... */ }\n public function execute() { /* ... */ }\n\n}\n\nclass Memory\n{\n public function load( $position, $data ) { /* ... */ }\n}\n\nclass HardDrive\n{\n public function read( $lba, $size ) { /* ... */ }\n}\n\n/* Facade */\nclass Computer\n{\n protected $cpu = null;\n protected $memory = null;\n protected $hardDrive = null;\n\n public function __construct()\n {\n $this->cpu = new CPU();\n $this->memory = new Memory();\n $this->hardDrive = new HardDrive();\n }\n\n public function startComputer()\n {\n $this->cpu->freeze();\n $this->memory->load( BOOT_ADDRESS, $this->hardDrive->read( BOOT_SECTOR, SECTOR_SIZE ) );\n $this->cpu->jump( BOOT_ADDRESS );\n $this->cpu->execute();\n }\n}\n\n/* Client */\n$facade = new Computer();\n$facade->startComputer();\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in JavaScript}}\n<syntaxhighlight lang=\"javascript\">\n/* Complex parts */\nvar CPU = function () {};\nCPU.prototype = {\n freeze: function () {\n console.log('CPU: freeze');\n },\n jump: function (position) {\n console.log('CPU: jump to ' + position);\n },\n execute: function () {\n console.log('CPU: execute');\n }\n};\n\nvar Memory = function () {};\nMemory.prototype = {\n load: function (position, data) {\n console.log('Memory: load \"' + data + '\" at ' + position);\n }\n};\n\nvar HardDrive = function () {};\nHardDrive.prototype = {\n read: function (lba, size) {\n console.log('HardDrive: read sector ' + lba + '(' + size + ' bytes)');\n return 'hdd data';\n }\n};\n\n/* Facade */\nvar Computer = function () {\n var cpu, memory, hardDrive;\n \n cpu = new CPU();\n memory = new Memory();\n hardDrive = new HardDrive();\n\n var constant = function (name) {\n var constants = {\n BOOT_ADDRESS: 0,\n BOOT_SECTOR: 0,\n SECTOR_SIZE: 512\n };\n\n return constants[name];\n };\n\n this.startComputer = function () {\n cpu.freeze();\n memory.load(constant('BOOT_ADDRESS'), hardDrive.read(constant('BOOT_SECTOR'), constant('SECTOR_SIZE')));\n cpu.jump(constant('BOOT_ADDRESS'));\n cpu.execute();\n }\n\n};\n\n/* Client */\nvar facade = new Computer();\nfacade.startComputer();\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in ActionScript 3.0}}\n<syntaxhighlight lang=\"actionscript\">\n/* Complex Parts */\n\n/* CPU.as */\npackage\n{\n public class CPU\n {\n public function freeze():void\n {\n trace(\"CPU::freeze\");\n }\n \n public function jump(addr:Number):void\n {\n trace(\"CPU::jump to\", String(addr));\n }\n \n public function execute():void\n {\n trace(\"CPU::execute\");\n }\n }\n}\n\n/* Memory.as */\npackage\n{\n import flash.utils.ByteArray;\n\n public class Memory\n {\n public function load(position:Number, data:ByteArray):void\n {\n trace(\"Memory::load position:\", position, \"data:\", data);\n }\n }\n}\n\n/* HardDrive.as */\npackage\n{\n import flash.utils.ByteArray;\n\n public class HardDrive\n {\n public function read(lba:Number, size:int):ByteArray\n {\n trace(\"HardDrive::read returning null\");\n return null;\n }\n }\n}\n\n/* The Facade */\n/* Computer.as */\npackage\n{\n public class Computer\n {\n public static const BOOT_ADDRESS:Number = 0x22;\n public static const BOOT_SECTOR:Number = 0x66;\n public static const SECTOR_SIZE:int = 0x200;\n \n private var _cpu:CPU;\n private var _memory:Memory;\n private var _hardDrive:HardDrive;\n \n public function Computer()\n {\n _cpu = new CPU();\n _memory = new Memory();\n _hardDrive = new HardDrive();\n }\n \n public function startComputer():void\n {\n _cpu.freeze();\n _memory.load(BOOT_ADDRESS, _hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));\n _cpu.jump(BOOT_ADDRESS);\n _cpu.execute();\n }\n }\n}\n\n/* Client.as : This is the application's Document class */\npackage\n{\n import flash.display.MovieClip;\n \n public class Client extends MovieClip\n { \n private var _computer:Computer;\n \n public function Client()\n {\n _computer = new Computer();\n _computer.startComputer();\n }\n }\n}\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in Scala}}\n\n<syntaxhighlight lang=\"scala\">\n/* Complex parts */\n\npackage intel {\n class CPU {\n def freeze() = ???\n def jump(position: Long) = ???\n def execute() = ???\n }\n}\n\npackage ram.plain {\n class Memory {\n def load(position: Long, data: Array[Byte]) = ???\n }\n}\n\npackage hdd {\n class HardDrive {\n def read(lba: Long, size: Int): Array[Byte] = ???\n }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"scala\">\n/* Facade */\n//imports for the facade\nimport common.patterns.intel.CPU\nimport common.patterns.ram.plain.Memory\nimport common.patterns.hdd.HardDrive\n\npackage pk {\n class ComputerFacade(conf: String) {\n val processor: CPU = new CPU\n val ram: Memory = new Memory\n val hd: HardDrive = new HardDrive\n\n val BOOT_ADDRESS: Long = ???\n val BOOT_SECTOR: Long = ???\n val SECTOR_SIZE: Int = ???\n\n def start() = {\n processor.freeze()\n ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE))\n processor.jump(BOOT_ADDRESS)\n processor.execute()\n }\n }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"scala\">\n//imports for your package\nimport common.patterns.pk.ComputerFacade\n\n/* Client */\n\nobject You {\n def main(args: Array[String]) {\n new ComputerFacade(\"conf\").start()\n }\n}\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in Delphi}}\n<syntaxhighlight lang=\"Delphi\">\nprogram Facade;\n\n{$APPTYPE CONSOLE}\n{$R *.res}\n\nuses\n System.SysUtils;\n\ntype\n (* complex parts - > Subsystem *)\n TCPU = class\n procedure Freeze;\n procedure Jump(position: Integer);\n procedure Execute;\n end;\n\n TMemory = class\n procedure Load(position: Integer; data: string);\n end;\n\n THardDrive = class\n function Read(lba, size: Integer): string;\n end;\n\n (* Facade *)\n TComputer = class\n fCPU: TCPU;\n fMemory: TMemory;\n fHardDrive: THardDrive;\n \n const\n BOOT_ADDRESS: Integer = 0;\n BOOT_SECTOR: Integer = 0;\n SECTOR_SIZE: Integer = 512;\n public\n procedure Start_Computer;\n constructor Create;\n end;\n\n { TCPU }\n\nprocedure TCPU.Execute;\nbegin\n WriteLn('CPU: execute');\nend;\n\nprocedure TCPU.Freeze;\nbegin\n WriteLn('CPU: freese');\nend;\n\nprocedure TCPU.Jump(position: Integer);\nbegin\n WriteLn('CPU: jump to ' + IntToStr(position));\nend;\n\n{ TMemory }\n\nprocedure TMemory.Load(position: Integer; data: string);\nbegin\n WriteLn('Memory: load \"' + data + '\" at ' + IntToStr(position));\nend;\n\n{ THardDrive }\n\nfunction THardDrive.Read(lba, size: Integer): string;\nbegin\n WriteLn('HardDrive: read sector ' + IntToStr(lba) + ' (' + IntToStr(size) +\n ' bytes)');\n Result := 'hdd data';\nend;\n\n{ TComputer }\n\nconstructor TComputer.Create;\nbegin\n fCPU := TCPU.Create;\n fMemory := TMemory.Create;\n fHardDrive := THardDrive.Create;\nend;\n\nprocedure TComputer.Start_Computer;\nbegin\n fCPU.Freeze;\n fMemory.Load(BOOT_ADDRESS, fHardDrive.Read(BOOT_SECTOR, SECTOR_SIZE));\n fCPU.Jump(BOOT_ADDRESS);\n fCPU.Execute;\nend;\n\nvar\n facad: TComputer;\n\nbegin\n try\n { TODO -oUser -cConsole Main : Insert code here }\n\n facad := TComputer.Create;\n facad.Start_Computer;\n \n WriteLn(#13#10 + 'Press any key to continue...');\n ReadLn;\n\n facad.Free;\n except\n on E: Exception do\n WriteLn(E.ClassName, ': ', E.Message);\n end;\nend.\n\n</syntaxhighlight>\n{{Hidden end}}"}},"i":0}}," <!-- ⇑ ONLY WRITE ABOVE THIS LINE! ⇑ -->"]}' id="mwAQ">

"},"page":{"wt":"{{{page|{{SUBPAGENAME}}}}} <!-- DO NOT MODIFY THIS LINE! -->"},"stage":{"wt":"25"},"stage date":{"wt":"29 Jan, 2014"},"stage comment":{"wt":"Add more illustrations."},"previous":{"wt":"Decorator"},"next":{"wt":"Factory method"},"content":{"wt":"A Facade pattern hides the complexities of the system and provides an interface to the client from where the client can access the system.\nDividing a system into subsystems helps reduce complexity. We need to minimize the communication and dependencies between subsystems. For this, we introduce a facade object that provides a single, simplified interface to the more general facilities of a subsystem.\n== Examples ==\nThe <code>SCP</code> command is a shortcut for SSH commands. A remote file copy could be done writing several commands with an SSH connection but it can be done in one command with <code>SCP</code>. So the <code>SCP</code> command is a facade for the SSH commands. Although it may not be coded in the object programming paradigm, it is a good illustration of the design pattern.\n== Cost ==\nThis pattern is very easy and has not additional cost.\n=== Creation ===\nThis pattern is very easy to create.\n=== Maintenance ===\nThis pattern is very easy to maintain.\n=== Removal ===\nThis pattern is very easy to remove too.\n== Advises ==\n* Do not use this pattern to mask only three or four method calls.\n== Implementations ==\n\n{{Java/Hidden begin|title=Implementation in Java}}\nThis is an abstract example of how a client (\"you\") interacts with a facade (the \"computer\") to a complex system (internal computer parts, like CPU and HardDrive).\n\n<syntaxhighlight lang=\"java\">\n/* Complex parts */\n\nclass CPU {\n public void freeze() { ... }\n public void jump(long position) { ... }\n public void execute() { ... }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"java\">\nclass Memory {\n public void load(long position, byte[] data) { ... }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"java\">\nclass HardDrive {\n public byte[] read(long lba, int size) { ... }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"java\">\n/* Facade */\n\nclass Computer {\n private CPU processor;\n private Memory ram;\n private HardDrive hd;\n\n public Computer() {\n this.processor = new CPU();\n this.ram = new Memory();\n this.hd = new HardDrive();\n }\n\n public void start() {\n processor.freeze();\n ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));\n processor.jump(BOOT_ADDRESS);\n processor.execute();\n }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"java\">\n/* Client */\n\nclass You {\n public static void main(String[] args) {\n Computer facade = new Computer();\n facade.start();\n }\n}\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in C#}}\n<syntaxhighlight lang=\"csharp\">\nusing System;\n\nnamespace Facade\n{\n\tpublic class CPU\n {\n\t\tpublic void Freeze() { }\n\t\tpublic void Jump(long addr) { }\n\t\tpublic void Execute() { }\n\t}\n\n\tpublic class Memory\n\t{\n\t\tpublic void Load(long position, byte[] data) { }\n }\n\n\tpublic class HardDrive\n\t{\n\t\tpublic byte[] Read(long lba, int size) { return null; }\n\t}\n\n\tpublic class Computer\n\t{\n\t\tvar cpu = new CPU();\n\t\tvar memory = new Memory();\n\t\tvar hardDrive = new HardDrive();\n\n\t\tpublic void StartComputer()\n\t\t{\n\t\t\tcpu.Freeze();\n\t\t\tmemory.Load(0x22, hardDrive.Read(0x66, 0x99));\n\t\t\tcpu.Jump(0x44);\n\t\t\tcpu.Execute();\n\t\t}\n\t}\n\n\tpublic class SomeClass\n\t{\n public static void Main(string[] args)\n {\n var facade = new Computer();\n facade.StartComputer();\n }\n }\n}\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in Ruby}}\n<syntaxhighlight lang=\"ruby\">\n# Complex parts\nclass CPU\n def freeze; puts 'CPU: freeze'; end\n def jump(position); puts \"CPU: jump to #{position}\"; end\n def execute; puts 'CPU: execute'; end\nend\n\nclass Memory\n def load(position, data)\n puts \"Memory: load #{data} at #{position}\"\n end\nend\n\nclass HardDrive\n def read(lba, size)\n puts \"HardDrive: read sector #{lba} (#{size} bytes)\"\n return 'hdd data'\n end\nend\n\n# Facade\nclass Computer\n BOOT_ADDRESS = 0\n BOOT_SECTOR = 0\n SECTOR_SIZE = 512\n\n def initialize\n @cpu = CPU.new\n @memory = Memory.new\n @hard_drive = HardDrive.new\n end\n\n def start_computer\n @cpu.freeze\n @memory.load(BOOT_ADDRESS, @hard_drive.read(BOOT_SECTOR, SECTOR_SIZE))\n @cpu.jump(BOOT_ADDRESS)\n @cpu.execute\n end\nend\n\n# Client\nfacade = Computer.new\nfacade.start_computer\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in Python}}\n<syntaxhighlight lang=\"python\">\n# Complex parts\nclass CPU:\n def freeze(self): pass\n def jump(self, position): pass\n def execute(self): pass\n \nclass Memory:\n def load(self, position, data): pass\n \nclass HardDrive:\n def read(self, lba, size): pass\n \n# Facade\nclass Computer:\n def __init__(self):\n self.cpu = CPU()\n self.memory = Memory()\n self.hard_drive = HardDrive()\n \n def start_computer(self):\n self.cpu.freeze()\n self.memory.load(0, self.hard_drive.read(0, 1024))\n self.cpu.jump(10)\n self.cpu.execute()\n \n# Client\nif __name__ == '__main__':\n facade = Computer()\n facade.start_computer()\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in PHP}}\n<syntaxhighlight lang=\"php\">\n/* Complex parts */\nclass CPU\n{\n public function freeze() { /* ... */ }\n public function jump( $position ) { /* ... */ }\n public function execute() { /* ... */ }\n\n}\n\nclass Memory\n{\n public function load( $position, $data ) { /* ... */ }\n}\n\nclass HardDrive\n{\n public function read( $lba, $size ) { /* ... */ }\n}\n\n/* Facade */\nclass Computer\n{\n protected $cpu = null;\n protected $memory = null;\n protected $hardDrive = null;\n\n public function __construct()\n {\n $this->cpu = new CPU();\n $this->memory = new Memory();\n $this->hardDrive = new HardDrive();\n }\n\n public function startComputer()\n {\n $this->cpu->freeze();\n $this->memory->load( BOOT_ADDRESS, $this->hardDrive->read( BOOT_SECTOR, SECTOR_SIZE ) );\n $this->cpu->jump( BOOT_ADDRESS );\n $this->cpu->execute();\n }\n}\n\n/* Client */\n$facade = new Computer();\n$facade->startComputer();\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in JavaScript}}\n<syntaxhighlight lang=\"javascript\">\n/* Complex parts */\nvar CPU = function () {};\nCPU.prototype = {\n freeze: function () {\n console.log('CPU: freeze');\n },\n jump: function (position) {\n console.log('CPU: jump to ' + position);\n },\n execute: function () {\n console.log('CPU: execute');\n }\n};\n\nvar Memory = function () {};\nMemory.prototype = {\n load: function (position, data) {\n console.log('Memory: load \"' + data + '\" at ' + position);\n }\n};\n\nvar HardDrive = function () {};\nHardDrive.prototype = {\n read: function (lba, size) {\n console.log('HardDrive: read sector ' + lba + '(' + size + ' bytes)');\n return 'hdd data';\n }\n};\n\n/* Facade */\nvar Computer = function () {\n var cpu, memory, hardDrive;\n \n cpu = new CPU();\n memory = new Memory();\n hardDrive = new HardDrive();\n\n var constant = function (name) {\n var constants = {\n BOOT_ADDRESS: 0,\n BOOT_SECTOR: 0,\n SECTOR_SIZE: 512\n };\n\n return constants[name];\n };\n\n this.startComputer = function () {\n cpu.freeze();\n memory.load(constant('BOOT_ADDRESS'), hardDrive.read(constant('BOOT_SECTOR'), constant('SECTOR_SIZE')));\n cpu.jump(constant('BOOT_ADDRESS'));\n cpu.execute();\n }\n\n};\n\n/* Client */\nvar facade = new Computer();\nfacade.startComputer();\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in ActionScript 3.0}}\n<syntaxhighlight lang=\"actionscript\">\n/* Complex Parts */\n\n/* CPU.as */\npackage\n{\n public class CPU\n {\n public function freeze():void\n {\n trace(\"CPU::freeze\");\n }\n \n public function jump(addr:Number):void\n {\n trace(\"CPU::jump to\", String(addr));\n }\n \n public function execute():void\n {\n trace(\"CPU::execute\");\n }\n }\n}\n\n/* Memory.as */\npackage\n{\n import flash.utils.ByteArray;\n\n public class Memory\n {\n public function load(position:Number, data:ByteArray):void\n {\n trace(\"Memory::load position:\", position, \"data:\", data);\n }\n }\n}\n\n/* HardDrive.as */\npackage\n{\n import flash.utils.ByteArray;\n\n public class HardDrive\n {\n public function read(lba:Number, size:int):ByteArray\n {\n trace(\"HardDrive::read returning null\");\n return null;\n }\n }\n}\n\n/* The Facade */\n/* Computer.as */\npackage\n{\n public class Computer\n {\n public static const BOOT_ADDRESS:Number = 0x22;\n public static const BOOT_SECTOR:Number = 0x66;\n public static const SECTOR_SIZE:int = 0x200;\n \n private var _cpu:CPU;\n private var _memory:Memory;\n private var _hardDrive:HardDrive;\n \n public function Computer()\n {\n _cpu = new CPU();\n _memory = new Memory();\n _hardDrive = new HardDrive();\n }\n \n public function startComputer():void\n {\n _cpu.freeze();\n _memory.load(BOOT_ADDRESS, _hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));\n _cpu.jump(BOOT_ADDRESS);\n _cpu.execute();\n }\n }\n}\n\n/* Client.as : This is the application's Document class */\npackage\n{\n import flash.display.MovieClip;\n \n public class Client extends MovieClip\n { \n private var _computer:Computer;\n \n public function Client()\n {\n _computer = new Computer();\n _computer.startComputer();\n }\n }\n}\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in Scala}}\n\n<syntaxhighlight lang=\"scala\">\n/* Complex parts */\n\npackage intel {\n class CPU {\n def freeze() = ???\n def jump(position: Long) = ???\n def execute() = ???\n }\n}\n\npackage ram.plain {\n class Memory {\n def load(position: Long, data: Array[Byte]) = ???\n }\n}\n\npackage hdd {\n class HardDrive {\n def read(lba: Long, size: Int): Array[Byte] = ???\n }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"scala\">\n/* Facade */\n//imports for the facade\nimport common.patterns.intel.CPU\nimport common.patterns.ram.plain.Memory\nimport common.patterns.hdd.HardDrive\n\npackage pk {\n class ComputerFacade(conf: String) {\n val processor: CPU = new CPU\n val ram: Memory = new Memory\n val hd: HardDrive = new HardDrive\n\n val BOOT_ADDRESS: Long = ???\n val BOOT_SECTOR: Long = ???\n val SECTOR_SIZE: Int = ???\n\n def start() = {\n processor.freeze()\n ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE))\n processor.jump(BOOT_ADDRESS)\n processor.execute()\n }\n }\n}\n</syntaxhighlight>\n\n<syntaxhighlight lang=\"scala\">\n//imports for your package\nimport common.patterns.pk.ComputerFacade\n\n/* Client */\n\nobject You {\n def main(args: Array[String]) {\n new ComputerFacade(\"conf\").start()\n }\n}\n</syntaxhighlight>\n{{Hidden end}}\n\n{{Java/Hidden begin|title=Implementation in Delphi}}\n<syntaxhighlight lang=\"Delphi\">\nprogram Facade;\n\n{$APPTYPE CONSOLE}\n{$R *.res}\n\nuses\n System.SysUtils;\n\ntype\n (* complex parts - > Subsystem *)\n TCPU = class\n procedure Freeze;\n procedure Jump(position: Integer);\n procedure Execute;\n end;\n\n TMemory = class\n procedure Load(position: Integer; data: string);\n end;\n\n THardDrive = class\n function Read(lba, size: Integer): string;\n end;\n\n (* Facade *)\n TComputer = class\n fCPU: TCPU;\n fMemory: TMemory;\n fHardDrive: THardDrive;\n \n const\n BOOT_ADDRESS: Integer = 0;\n BOOT_SECTOR: Integer = 0;\n SECTOR_SIZE: Integer = 512;\n public\n procedure Start_Computer;\n constructor Create;\n end;\n\n { TCPU }\n\nprocedure TCPU.Execute;\nbegin\n WriteLn('CPU: execute');\nend;\n\nprocedure TCPU.Freeze;\nbegin\n WriteLn('CPU: freese');\nend;\n\nprocedure TCPU.Jump(position: Integer);\nbegin\n WriteLn('CPU: jump to ' + IntToStr(position));\nend;\n\n{ TMemory }\n\nprocedure TMemory.Load(position: Integer; data: string);\nbegin\n WriteLn('Memory: load \"' + data + '\" at ' + IntToStr(position));\nend;\n\n{ THardDrive }\n\nfunction THardDrive.Read(lba, size: Integer): string;\nbegin\n WriteLn('HardDrive: read sector ' + IntToStr(lba) + ' (' + IntToStr(size) +\n ' bytes)');\n Result := 'hdd data';\nend;\n\n{ TComputer }\n\nconstructor TComputer.Create;\nbegin\n fCPU := TCPU.Create;\n fMemory := TMemory.Create;\n fHardDrive := THardDrive.Create;\nend;\n\nprocedure TComputer.Start_Computer;\nbegin\n fCPU.Freeze;\n fMemory.Load(BOOT_ADDRESS, fHardDrive.Read(BOOT_SECTOR, SECTOR_SIZE));\n fCPU.Jump(BOOT_ADDRESS);\n fCPU.Execute;\nend;\n\nvar\n facad: TComputer;\n\nbegin\n try\n { TODO -oUser -cConsole Main : Insert code here }\n\n facad := TComputer.Create;\n facad.Start_Computer;\n \n WriteLn(#13#10 + 'Press any key to continue...');\n ReadLn;\n\n facad.Free;\n except\n on E: Exception do\n WriteLn(E.ClassName, ': ', E.Message);\n end;\nend.\n\n</syntaxhighlight>\n{{Hidden end}}"}},"i":0}}]}' id="mwAg">

Decorator Computer Science Design Patterns
Facade
Factory method
Table of content

A Facade pattern hides the complexities of the system and provides an interface to the client from where the client can access the system. Dividing a system into subsystems helps reduce complexity. We need to minimize the communication and dependencies between subsystems. For this, we introduce a facade object that provides a single, simplified interface to the more general facilities of a subsystem.

Examples

The SCP command is a shortcut for SSH commands. A remote file copy could be done writing several commands with an SSH connection but it can be done in one command with SCP. So the SCP command is a facade for the SSH commands. Although it may not be coded in the object programming paradigm, it is a good illustration of the design pattern.

Cost

This pattern is very easy and has not additional cost.

Creation

This pattern is very easy to create.

Maintenance

This pattern is very easy to maintain.

Removal

This pattern is very easy to remove too.

Advises

  • Do not use this pattern to mask only three or four method calls.

Implementations

Implementation in Java

This is an abstract example of how a client ("you") interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive).

/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}
class Memory {
    public void load(long position, byte[] data) { ... }
}
class HardDrive {
    public byte[] read(long lba, int size) { ... }
}
/* Facade */

class Computer {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public Computer() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}
/* Client */

class You {
    public static void main(String[] args) {
        Computer facade = new Computer();
        facade.start();
    }
}
Implementation in C#
using System;

namespace Facade
{
	public class CPU
        {
		public void Freeze() { }
		public void Jump(long addr) { }
		public void Execute() { }
	}

	public class Memory
	{
		public void Load(long position, byte[] data) { }
        }

	public class HardDrive
	{
		public byte[] Read(long lba, int size) { return null; }
	}

	public class Computer
	{
		var cpu = new CPU();
		var memory = new Memory();
		var hardDrive = new HardDrive();

		public void StartComputer()
		{
			cpu.Freeze();
			memory.Load(0x22, hardDrive.Read(0x66, 0x99));
			cpu.Jump(0x44);
			cpu.Execute();
		}
	}

	public class SomeClass
	{
            public static void Main(string[] args)
            {
                var facade = new Computer();
                facade.StartComputer();
            }
        }
}
Implementation in Ruby
# Complex parts
class CPU
  def freeze; puts 'CPU: freeze'; end
  def jump(position); puts "CPU: jump to #{position}"; end
  def execute; puts 'CPU: execute'; end
end

class Memory
  def load(position, data)
    puts "Memory: load #{data} at #{position}"
  end
end

class HardDrive
  def read(lba, size)
    puts "HardDrive: read sector #{lba} (#{size} bytes)"
    return 'hdd data'
  end
end

# Facade
class Computer
  BOOT_ADDRESS = 0
  BOOT_SECTOR = 0
  SECTOR_SIZE = 512

  def initialize
    @cpu = CPU.new
    @memory = Memory.new
    @hard_drive = HardDrive.new
  end

  def start_computer
    @cpu.freeze
    @memory.load(BOOT_ADDRESS, @hard_drive.read(BOOT_SECTOR, SECTOR_SIZE))
    @cpu.jump(BOOT_ADDRESS)
    @cpu.execute
  end
end

# Client
facade = Computer.new
facade.start_computer
Implementation in Python
# Complex parts
class CPU:
    def freeze(self): pass
    def jump(self, position): pass
    def execute(self): pass
 
class Memory:
    def load(self, position, data): pass
 
class HardDrive:
    def read(self, lba, size): pass
 
# Facade
class Computer:
    def __init__(self):
        self.cpu = CPU()
        self.memory = Memory()
        self.hard_drive = HardDrive()
    
    def start_computer(self):
        self.cpu.freeze()
        self.memory.load(0, self.hard_drive.read(0, 1024))
        self.cpu.jump(10)
        self.cpu.execute()
 
# Client
if __name__ == '__main__':
    facade = Computer()
    facade.start_computer()
Implementation in PHP
cpu = new CPU();\n $this->memory = new Memory();\n $this->hardDrive = new HardDrive();\n }\n\n public function startComputer()\n {\n $this->cpu->freeze();\n $this->memory->load( BOOT_ADDRESS, $this->hardDrive->read( BOOT_SECTOR, SECTOR_SIZE ) );\n $this->cpu->jump( BOOT_ADDRESS );\n $this->cpu->execute();\n }\n}\n\n/* Client */\n$facade = new Computer();\n$facade->startComputer();\n"}}' id="mwA6w">
/* Complex parts */
class CPU
{
    public function freeze() { /* ... */ }
    public function jump( $position ) { /* ... */ }
    public function execute() { /* ... */ }

}

class Memory
{
    public function load( $position, $data ) { /* ... */ }
}

class HardDrive
{
    public function read( $lba, $size ) { /* ... */ }
}

/* Facade */
class Computer
{
    protected $cpu = null;
    protected $memory = null;
    protected $hardDrive = null;

    public function __construct()
    {
        $this->cpu = new CPU();
        $this->memory = new Memory();
        $this->hardDrive = new HardDrive();
    }

    public function startComputer()
    {
        $this->cpu->freeze();
        $this->memory->load( BOOT_ADDRESS, $this->hardDrive->read( BOOT_SECTOR, SECTOR_SIZE ) );
        $this->cpu->jump( BOOT_ADDRESS );
        $this->cpu->execute();
    }
}

/* Client */
$facade = new Computer();
$facade->startComputer();
Implementation in JavaScript
/* Complex parts */
var CPU = function () {};
CPU.prototype = {
  freeze: function () {
    console.log('CPU: freeze');
  },
  jump: function (position) {
    console.log('CPU: jump to ' + position);
  },
  execute: function () {
    console.log('CPU: execute');
  }
};

var Memory = function () {};
Memory.prototype = {
  load: function (position, data) {
    console.log('Memory: load "' + data + '" at ' + position);
  }
};

var HardDrive = function () {};
HardDrive.prototype = {
  read: function (lba, size) {
    console.log('HardDrive: read sector ' + lba + '(' + size + ' bytes)');
    return 'hdd data';
  }
};

/* Facade */
var Computer = function () {
  var cpu, memory, hardDrive;
  
  cpu = new CPU();
  memory = new Memory();
  hardDrive = new HardDrive();

  var constant = function (name) {
    var constants = {
      BOOT_ADDRESS: 0,
      BOOT_SECTOR: 0,
      SECTOR_SIZE: 512
    };

    return constants[name];
  };

  this.startComputer = function () {
    cpu.freeze();
    memory.load(constant('BOOT_ADDRESS'), hardDrive.read(constant('BOOT_SECTOR'), constant('SECTOR_SIZE')));
    cpu.jump(constant('BOOT_ADDRESS'));
    cpu.execute();
  }

};

/* Client */
var facade = new Computer();
facade.startComputer();
Implementation in ActionScript 3.0
/* Complex Parts */

/* CPU.as */
package
{
    public class CPU
    {
        public function freeze():void
        {
            trace("CPU::freeze");
        }
        
        public function jump(addr:Number):void
        {
            trace("CPU::jump to", String(addr));
        }
        
        public function execute():void
        {
            trace("CPU::execute");
        }
    }
}

/* Memory.as */
package
{
    import flash.utils.ByteArray;

    public class Memory
    {
        public function load(position:Number, data:ByteArray):void
        {
            trace("Memory::load position:", position, "data:", data);
        }
    }
}

/* HardDrive.as */
package
{
    import flash.utils.ByteArray;

    public class HardDrive
    {
        public function read(lba:Number, size:int):ByteArray
        {
            trace("HardDrive::read returning null");
            return null;
        }
    }
}

/* The Facade */
/* Computer.as */
package
{
    public class Computer
    {
        public static const BOOT_ADDRESS:Number = 0x22;
        public static const BOOT_SECTOR:Number = 0x66;
        public static const SECTOR_SIZE:int = 0x200;
        
        private var _cpu:CPU;
        private var _memory:Memory;
        private var _hardDrive:HardDrive;
        
        public function Computer()
        {
            _cpu = new CPU();
            _memory = new Memory();
            _hardDrive = new HardDrive();
        }
        
        public function startComputer():void
        {
            _cpu.freeze();
            _memory.load(BOOT_ADDRESS, _hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
            _cpu.jump(BOOT_ADDRESS);
            _cpu.execute();
        }
    }
}

/* Client.as : This is the application's Document class */
package
{
    import flash.display.MovieClip;
    
    public class Client extends MovieClip
    {       
        private var _computer:Computer;
        
        public function Client()
        {
            _computer = new Computer();
            _computer.startComputer();
        }
    }
}
Implementation in Scala
/* Complex parts */

package intel {
  class CPU {
    def freeze() = ???
    def jump(position: Long) = ???
    def execute() = ???
  }
}

package ram.plain {
  class Memory {
    def load(position: Long, data: Array[Byte]) = ???
  }
}

package hdd {
  class HardDrive {
    def read(lba: Long, size: Int): Array[Byte]  = ???
  }
}
/* Facade */
//imports for the facade
import common.patterns.intel.CPU
import common.patterns.ram.plain.Memory
import common.patterns.hdd.HardDrive

package pk {
  class ComputerFacade(conf: String) {
    val processor: CPU = new CPU
    val ram: Memory = new Memory
    val hd: HardDrive = new HardDrive

    val BOOT_ADDRESS: Long = ???
    val BOOT_SECTOR: Long = ???
    val SECTOR_SIZE: Int = ???

    def start() = {
      processor.freeze()
      ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE))
      processor.jump(BOOT_ADDRESS)
      processor.execute()
    }
  }
}
//imports for your package
import common.patterns.pk.ComputerFacade

/* Client */

object You {
  def main(args: Array[String]) {
    new ComputerFacade("conf").start()
  }
}
Implementation in Delphi
Subsystem *)\n TCPU = class\n procedure Freeze;\n procedure Jump(position: Integer);\n procedure Execute;\n end;\n\n TMemory = class\n procedure Load(position: Integer; data: string);\n end;\n\n THardDrive = class\n function Read(lba, size: Integer): string;\n end;\n\n (* Facade *)\n TComputer = class\n fCPU: TCPU;\n fMemory: TMemory;\n fHardDrive: THardDrive;\n \n const\n BOOT_ADDRESS: Integer = 0;\n BOOT_SECTOR: Integer = 0;\n SECTOR_SIZE: Integer = 512;\n public\n procedure Start_Computer;\n constructor Create;\n end;\n\n { TCPU }\n\nprocedure TCPU.Execute;\nbegin\n WriteLn('CPU: execute');\nend;\n\nprocedure TCPU.Freeze;\nbegin\n WriteLn('CPU: freese');\nend;\n\nprocedure TCPU.Jump(position: Integer);\nbegin\n WriteLn('CPU: jump to ' + IntToStr(position));\nend;\n\n{ TMemory }\n\nprocedure TMemory.Load(position: Integer; data: string);\nbegin\n WriteLn('Memory: load \"' + data + '\" at ' + IntToStr(position));\nend;\n\n{ THardDrive }\n\nfunction THardDrive.Read(lba, size: Integer): string;\nbegin\n WriteLn('HardDrive: read sector ' + IntToStr(lba) + ' (' + IntToStr(size) +\n ' bytes)');\n Result := 'hdd data';\nend;\n\n{ TComputer }\n\nconstructor TComputer.Create;\nbegin\n fCPU := TCPU.Create;\n fMemory := TMemory.Create;\n fHardDrive := THardDrive.Create;\nend;\n\nprocedure TComputer.Start_Computer;\nbegin\n fCPU.Freeze;\n fMemory.Load(BOOT_ADDRESS, fHardDrive.Read(BOOT_SECTOR, SECTOR_SIZE));\n fCPU.Jump(BOOT_ADDRESS);\n fCPU.Execute;\nend;\n\nvar\n facad: TComputer;\n\nbegin\n try\n { TODO -oUser -cConsole Main : Insert code here }\n\n facad := TComputer.Create;\n facad.Start_Computer;\n \n WriteLn(#13#10 + 'Press any key to continue...');\n ReadLn;\n\n facad.Free;\n except\n on E: Exception do\n WriteLn(E.ClassName, ': ', E.Message);\n end;\nend.\n\n"}}" id="mwCNs">
program Facade;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils;

type
  (* complex parts - > Subsystem *)
  TCPU = class
    procedure Freeze;
    procedure Jump(position: Integer);
    procedure Execute;
  end;

  TMemory = class
    procedure Load(position: Integer; data: string);
  end;

  THardDrive = class
    function Read(lba, size: Integer): string;
  end;

  (* Facade *)
  TComputer = class
    fCPU: TCPU;
    fMemory: TMemory;
    fHardDrive: THardDrive;
    
  const
    BOOT_ADDRESS: Integer = 0;
    BOOT_SECTOR: Integer = 0;
    SECTOR_SIZE: Integer = 512;
  public
    procedure Start_Computer;
    constructor Create;
  end;

  { TCPU }

procedure TCPU.Execute;
begin
  WriteLn('CPU: execute');
end;

procedure TCPU.Freeze;
begin
  WriteLn('CPU: freese');
end;

procedure TCPU.Jump(position: Integer);
begin
  WriteLn('CPU: jump to ' + IntToStr(position));
end;

{ TMemory }

procedure TMemory.Load(position: Integer; data: string);
begin
  WriteLn('Memory: load "' + data + '" at ' + IntToStr(position));
end;

{ THardDrive }

function THardDrive.Read(lba, size: Integer): string;
begin
  WriteLn('HardDrive: read sector ' + IntToStr(lba) + ' (' + IntToStr(size) +
    ' bytes)');
  Result := 'hdd data';
end;

{ TComputer }

constructor TComputer.Create;
begin
  fCPU := TCPU.Create;
  fMemory := TMemory.Create;
  fHardDrive := THardDrive.Create;
end;

procedure TComputer.Start_Computer;
begin
  fCPU.Freeze;
  fMemory.Load(BOOT_ADDRESS, fHardDrive.Read(BOOT_SECTOR, SECTOR_SIZE));
  fCPU.Jump(BOOT_ADDRESS);
  fCPU.Execute;
end;

var
  facad: TComputer;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }

    facad := TComputer.Create;
    facad.Start_Computer;
    
    WriteLn(#13#10 + 'Press any key to continue...');
    ReadLn;

    facad.Free;
  except
    on E: Exception do
      WriteLn(E.ClassName, ': ', E.Message);
  end;
end.


Clipboard

To do:
Add more illustrations.


Decorator Computer Science Design Patterns
Facade
Factory method


You have questions about this page?
Ask it here:


Create a new page on this book: