티스토리 뷰

Java

Template Method Pattern

techbard 2016.07.20 21:43

TemplateMethod.zip



# Template.java


public abstract class Template {

    public boolean isOn;


    public Template() {

this.isOn = false;

    }


    abstract void welcome();

    abstract void turnOn();

    abstract void turnOff();

    

    public final void setup() {

if (!isOn) {

   welcome();

   turnOn();

}

    }


    public final void toggleSwitch() {

if (this.isOn)

   turnOff();

else {

   welcome();

   turnOn();

}

    }

}



# PC.java


public class PC extends Template {


    @Override

    void welcome() {

System.out.println("Welcome to My PC!");

    }

    

    @Override

    void turnOn() {

super.isOn = true;

System.out.println("PC is on.");

    }


    @Override

    void turnOff() {

super.isOn = false;

System.out.println("PC is off.");

    }

}



# TV.java


public class TV extends Template {


    @Override

    void welcome() {

System.out.println("Welcome to My TV!");

    }

    

    @Override

    void turnOn() {

super.isOn = true;

System.out.println("TV is on.");

    }


    @Override

    void turnOff() {

super.isOn = false;

System.out.println("TV is off.");

    }

}


# Main.java


public class Main {

    public static void main(String[] args) {

PC pc = new PC();

// startup and welcome screen

pc.setup();

// PC off

pc.toggleSwitch();

// startup and welcome screen again

pc.toggleSwitch();

System.out.println("====================");

TV tv = new TV();

tv.setup();

tv.toggleSwitch();

    }

}



# 결과


Welcome to My PC!

PC is on.

PC is off.

Welcome to My PC!

PC is on.

====================

Welcome to My TV!

TV is on.

TV is off.


댓글
댓글쓰기 폼
공지사항
Total
394,929
Today
0
Yesterday
28
«   2018/11   »
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
글 보관함