Template pattern 是很容易理解的,父类只声明一些函数,并不去实现,具体的实现让子类去自己实现。
Usage in jdk:
All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer 。
-
package template;
-
-
abstract class PurchaseOrderTemplate{
-
public abstract void doSelect();
-
public abstract void doPayment();
-
-
public final void doPack(){
-
System.out.println("Gift wrap done");
-
}
-
-
public abstract void doDelivery();
-
-
public final void processOrder(){
-
doSelect();
-
doPayment();
-
doPack();
-
doDelivery();
-
}
-
}
-
-
class StorePurchaseOrder extends PurchaseOrderTemplate{
-
@Override
-
public void doSelect(){
-
System.out.println("Customer chooses the item from shelf");
-
}
-
-
@Override
-
public void doPayment(){
-
System.out.println("Pays at counter through cash/POS");
-
}
-
-
@Override
-
public void doDelivery(){
-
System.out.println("Item delivered to in delivery counter");
-
}
-
}
-
-
class OnlinePurchaseOrder extends PurchaseOrderTemplate{
-
@Override
-
public void doSelect(){
-
System.out.println("Item added to online shopping cart");
-
System.out.println("Get gift wrap preference.");
-
System.out.println("Get delivery address");
-
}
-
-
@Override
-
public void doPayment(){
-
System.out.println("Online payment through Netbanking/Cards");
-
}
-
-
@Override
-
public void doDelivery(){
-
System.out.println("Ship the item through post to delivery address");
-
}
-
}
-
-
-
public class TemplatePatternDemo {
-
public static void main(String[] args){
-
PurchaseOrderTemplate online = new OnlinePurchaseOrder();
-
online.processOrder();
-
PurchaseOrderTemplate offline = new StorePurchaseOrder();
-
offline.processOrder();
-
}
-
}
阅读(548) | 评论(0) | 转发(0) |