Design mode: face -- appearance mode

Appearance mode

Appearance mode is to solve the dependency between classes and family of classes. Like spring, you can configure the relationship between classes into a configuration file. Appearance mode is to put their relationship into a Facade class, reducing the coupling between classes. There is no interface involved in this mode. Look at the class diagram below: (let's take the startup process of a computer as an example)

 

The code is as follows:

class CPU {

    public void startUp () {
        System.out.println("cpu startup");
    }

    public void shutdown() {
        System.out.println("cpu shotdown");
    }
}

class Disk {
    public void startUp () {
        System.out.println("disk startup");
    }

    public void shutdown() {
        System.out.println("disk shotdown");
    }
}


class Memory {
    public void startUp () {
        System.out.println("memory startup");
    }

    public void shutdown() {
        System.out.println("memory shotdown");
    }
}

class Computer {
    private CPU cpu;
    private Memory memory;
    private Disk disk;

    public Computer() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.disk = new Disk();
    }

    public void startUp() {
        System.out.println("start the computer!");
        cpu.startUp();
        memory.startUp();
        disk.startUp();
        System.out.println("start computer finished!");
    }

    public void shutdown(){
        System.out.println("begin to close the computer!");
        cpu.shutdown();
        memory.shutdown();
        disk.shutdown();
        System.out.println("computer closed!");
    }
}

public class MainClass {
    public static void main(String[] args) {
        Computer computer = new Computer();
        computer.shutdown();
        computer.startUp();
    }
}

If we don't have a Computer class, then the CPU, Memory and Disk will hold instances and have relationships with each other, which will cause serious dependency. Modifying one class may lead to the modification of other classes. This is not what we want to see. With a Computer class, the relationship between them is put in the Computer class, which plays a role in understanding the coupling. So, we can It's appearance mode!

 

Output test results:

begin to close the computer!
cpu shotdown
memory shotdown
disk shotdown
computer closed!
start the computer!
cpu startup
memory startup
disk startup
start computer finished!

Tags: Spring

Posted on Sat, 09 Nov 2019 10:51:51 -0500 by rawky1976