廣告

2015年3月30日 星期一

[design pattern] [java] Template Pattern

template pttern:
use abstract class to define template(behavior)
to execute its methods.
And use some class to extend it.
to override the method of superclass.



Programmer

package com.test.templatepattern;

public abstract class Programmer {

 abstract boolean getUP();
 abstract boolean atCompany();
 abstract boolean Home();
 
 public void dailyRoutine(){
  getUP();
  atCompany();
  Home();
 }
}



Seven
package com.test.templatepattern;

public class Seven extends Programmer {

 @Override
 boolean getUP() {
  System.out.println("sleeping");
  return false;
 }

 @Override
 boolean atCompany() {
  System.out.println("coding");
  return false;
 }

 @Override
 boolean Home() {
  System.out.println("sleeping");
  return false;
 }

}




Leo
package com.test.templatepattern;

public class Leo extends Programmer {

 @Override
 boolean getUP() {
  System.out.println("meeting");
  return false;
 }

 @Override
 boolean atCompany() {
  System.out.println("meeting");
  return false;
 }

 @Override
 boolean Home() {
  System.out.println("meeting");
  return false;
 }

}




Lewis
package com.test.templatepattern;

public class Lewis extends Programmer {

 @Override
 boolean getUP() {
  System.out.println("coding");
  return false;
 }

 @Override
 boolean atCompany() {
  System.out.println("coding");
  return false;
 }

 @Override
 boolean Home() {
  System.out.println("coding");
  return false;
 }

}




testTemplatePattern

package com.test.templatepattern;

public class testTemplatePattern {

 public static void main(String[] args) {
  /*
  template pttern:
  use abstract class to define template(behavior) 
  to execute its methods.
  And use some class to extend it.
  to override the method of superclass.
  */
  
    Programmer lewis = new Lewis();
    lewis.dailyRoutine();
       System.out.println();
      
       Programmer leo = new Leo();
       leo.dailyRoutine();
       System.out.println();
       
       Programmer seven = new Seven();
       seven.dailyRoutine();
       System.out.println();
 }

}



console
coding
coding
coding

meeting
meeting
meeting

sleeping
coding
sleeping



沒有留言:

張貼留言