What is the facade design pattern?
Is facade a class which contains a lot of other classes?
What makes it a design pattern? To me, it is like a normal class.
Can you explain to me this Facade pattern?
Solution 1:
A design pattern is a common way of solving a recurring problem. Classes in all design patterns are just normal classes. What is important is how they are structured and how they work together to solve a given problem in the best possible way.
The Facade design pattern simplifies the interface to a complex system; because it is usually composed of all the classes which make up the subsystems of the complex system.
A Facade shields the user from the complex details of the system and provides them with a simplified view
of it which is easy to use
. It also decouples
the code that uses the system from the details of the subsystems, making it easier to modify the system later.
http://www.dofactory.com/Patterns/PatternFacade.aspx
http://www.blackwasp.co.uk/Facade.aspx
Also, what is important while learning design patterns is to be able to recognize which pattern fits your given problem and then using it appropriately. It is a very common thing to misuse a pattern or trying to fit it to some problem just because you know it. Be aware of those pitfalls while learning\using design patterns.
Solution 2:
Wikipedia has a great example of Facade pattern.
/* 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 ComputerFacade {
private CPU processor;
private Memory ram;
private HardDrive hd;
public ComputerFacade() {
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) {
ComputerFacade computer = new ComputerFacade();
computer.start();
}
}