Ad Code

What is the basic purpose of using Facade pattern

What is the basic purpose of using Facade pattern? isn't it make our code more complex all the communication with other objects takes place through another object restricting direct access to system objects?  Kindly give any example of facade pattern application; provide c++ code if applicable.



A facade pattern provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystem easier to use. With the help of a facade pattern, a complex system can be made easy to understand using an easy to use interface for the system. It does not make the code complex.

This is an example of how a client 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 cpu;
    private Memory memory;
    private HardDrive hardDrive;

    public Computer() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
    }

    public void startComputer() {
        cpu.freeze();
        memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
        cpu.jump(BOOT_ADDRESS);
        cpu.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        Computer facade = new Computer();
        facade.startComputer();
    }
}

So from the above example, it can be seen that a facade pattern provides a single, simplified interface to the many, potentially complex, individual interfaces within the subsystem. For the above example, only one interface (startComputer) is required for all the other interfaces (freeze, load, jump, execute) of the system.
Reactions

Post a Comment

0 Comments