设计模式快速参考-模板方法模式

阅读更多

 

abstract class TravelTemplate{
   public void travel(){
      //上车
      getOnBus();
      //去目的地
      goto(“目的地”)
      //吃饭
      eat();
      //下车
     getOffBus();
     //如果想拍照,就拍照
     if(wantToTakePhoto){
        takePhoto();
     }
     //如果想上厕所,就上厕所
     if(wantToGotoRestroom){
        gotoRestRoom();
     }
     //上车回家
     getOnBus();
     goHome();
  }
  protected void goto(String str){
  }
  protected void getOnBus(){
  }
  protected void eat{
  }
  protected void takePhoto(){
  }
  protected void gotoRestRoom(){
  }
  protected void getOffBus(){
  }
  protected void goHome(){
  }
}

class HangzhouTravelTemplate extends TravelTemplate{
}

class BeijingTravelTemplate extends TravelTemplate{
}

class Tourist{
   private TravelTemplate template;
   pulic void setTravelTemplate(TravelTemplate template){
   }
   public travel(){
      template.travel();
   }
}
 

 


Client:

 

TravelTemplate hangzhouTemplate =  new HangzhouTravelTemplate(“杭州一日游”)
TravelTemplate beijingTemplate =  new BeijingTravelTemplate(“北京奥运两日游”)
Tourist zhangSan = new Tourist(“张三”);

//杭州一日游
zhangSan.setTemplate(travelTemplate);
zhangSan.travel();

//北京两日游
zhangSan.setTemplate(beijingTemplate);
zhangSan.travel();
 

 

你可能感兴趣的:(设计模式)