Design mode appearance mode

  • Appearance mode principle

  • A home theater project:

    • Introduce a second remote control in the home theater to call various functions and put them on one interface
    • The appearance mode provides a unified interface, visiting a group of function related interfaces in the subsystem. The appearance mode defines a high-level interface, making the subsystem easier to use.
    • Appearance mode is to use a function to call many functions in the system
  • Code explanation:

package waiguan;
/**
* Created with IntelliJ IDEA.
* Description:
* User: wjx
* Date: 2019-04-20
* Time: 19:44
*/
public class DVD {
    private static DVD dvd = null;
    private DVD(){


    }
    public static DVD getInstance(){
        if(dvd == null){
            dvd = new DVD();
        }
        return dvd;
    }
    public void on(){
        System.out.println("Dvd is on");
    }
    public void off(){
        System.out.println("Dvd is off");
    }
}


package waiguan;


/**
* Created with IntelliJ IDEA.
* Description:
* User: wjx
* Date: 2019-04-20
* Time: 19:44
*/
public class Popcorn {
    private Popcorn(){


    }
    private static Popcorn popcorn = null;
    public static Popcorn getInstance(){
        if(popcorn==null){
            popcorn = new Popcorn();
        }
        return popcorn;
    }
    public void on(){
        System.out.println("Popcorn is on");
    }
    public void off(){
        System.out.println("Popcorn is off");
    }
}

  • Unified call by home theater:
package waiguan;

/**
* Created with IntelliJ IDEA.
* Description:
* User: wjx
* Date: 2019-04-20
* Time: 19:48
*/
public class HomeMedia {
    private DVD dvd;
    private Popcorn popcorn;
    public HomeMedia(){
        dvd = DVD.getInstance();
        popcorn = Popcorn.getInstance();
    }
    public void on(){
        dvd.on();
        popcorn.on();
    }
    public void off(){
        dvd.off();
        popcorn.off();
    }
}

  • Test:
package waiguan;

/**
* Created with IntelliJ IDEA.
* Description:
* User: wjx
* Date: 2019-04-20
* Time: 19:50
*/
public class MainTest {
    public static void main(String[] args) {
        HomeMedia homeMedia = new HomeMedia();
        homeMedia.on();
        homeMedia.off();
    }
}


  • Appearance mode reduces the external coupling of the objects in the system, so adding a function does not need to change the remote control, only the corresponding function is needed to make the system decouple from the external.
  • Comparison of appearance mode and adapter mode:
    • Adapter pattern: an adapter transforms the interface of one class and object into another pattern

    • Presentation of simplified functions of external functions provided by appearance mode system

Keywords: IntelliJ IDEA

Added by Syntac on Sat, 16 Nov 2019 20:01:15 +0200