Proxy - Structural Design Pattern

Proxy - Structural Design Pattern

2019, Feb 11    

🎱 Proxy

Using the proxy pattern, a class represents the functionality of another class.

interface Door {
    public void open();
    public void close();
}
class LabDoor implements Door {
    public void open() {
        // "Opening lab door";
    }
    public void close() {
        // "Closing the lab door";
    }
}
class SecuredDoor{
    protected Door door;
    public SecuredDoor(Door door) {
        this.door = door;
    }
    public void open(String password) {
        if (this.authenticate(password)) {
            this.door.open();
        } else {
            // "Error you are not allowed";
        }
    }
    public boolean authenticate(String password) {
        return password == "$ecr@t";
    }
    public void close() {
        this.door.close();
    }
}

Door door = new SecuredDoor(new LabDoor());
door.open("invalid"); // Big no! It ain't possible.

Door door.open("$ecr@t"); // Opening lab door
door.close(); // Closing lab door