经典代码:
//相当于接口InA
public interface BoomWTC{
//获得拉登的决定
public benLaDengDecide();
// 执行轰炸世贸
public void boom();
}
//相当于class A
public class At$911 implements BoomWTC{//相当于【背景1】
private boolean decide;
private TerroristAttack ta;//相当于【背景2】
public At$911(){
Date now=new Date();
SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm");
this.dicede= myFmt.format(dt).equals("01/09/11 09:44");
this.ta=new TerroristAttack();
}
//获得拉登的决定
public boolean benLaDengDecide(){
return decide;
}
// 执行轰炸世贸
public void boom(){
ta.attack(new At$911);//class A调用class B的方法传入自己的对象,相当于【you call me】
}
}
//相当于class B
public class TerroristAttack{
public TerroristAttack(){
}
public attack(BoomWTC bmw){//这相当于【背景3】
if(bmw.benLaDengDecide()){//class B在方法中回调class A的方法,相当于【i call you back】
//let's go.........
}
}
}
1,模板类
package com.pattern.template;
public abstract class CaffeineBeverageWithHook {
void prepareRecipe(){
boilWater();
brew();
pourInCup();
if(customerWantsCondiments()){
addCondiments();
}
}
abstract void brew();
abstract void addCondiments();
void boilWater(){
System.out.println("Boiling water");
}
void pourInCup(){
System.out.println("Pouring into cup");
}
boolean customerWantsCondiments(){
return true;
}
}
package com.pattern.template;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CoffeeWithHook extends CaffeineBeverageWithHook{
/**
* @see com.pattern.template.CaffeineBeverageWithHook#brew()
*/
@Override
void brew() {
System.out.println("Dripping Coffee through filter");
}
/**
* @see com.pattern.template.CaffeineBeverageWithHook#addCondiments()
*/
@Override
void addCondiments() {
System.out.println("Adding Sugar and Milk");
}
public boolean customerWantsCondiments(){
String answer = getUserInput();
if(answer.toLowerCase().startsWith("y")){
return true;
} else{
return false;
}
}
private String getUserInput(){
String answer = null;
System.out.println("Would you like milk and sugar with your coffee (y/n)?");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
answer = in.readLine();
} catch (IOException e) {
System.out.println("IO Exception!");
}
if(answer == null){
return "no";
}
return answer;
}
}
package com.pattern.template;
public class BeverageTestDrive {
public static void main(String[] args) {
CoffeeWithHook coffeeHook = new CoffeeWithHook();
System.out.println("\nMaking tea...");
coffeeHook.prepareRecipe();
}
}