if(request.getLeaveDays()<20) { System.out.println(\副总经理\+ name + \审批员工\+ request.getLeaveName() + \的请假条,请假天数为\天。\ } else { if(this.successor!=null) { this.successor.handleRequest(request); } } } }
模板方法
实例一:银行业务办理流程 在银行办理业务时,一般都包含几个基本步骤,首先需要取号排队,然后办理具体业务,最后需要对银行工作人员进行评分。无论具体业务是取款、存款还是转账,其基本流程都一样。现使用模板方法模式模拟银行业务办理流程。
public abstract class BankTemplateMethod {
public void takeNumber() { System.out.println(\取号排队。\ } public abstract void transact(); public void evaluate() { System.out.println(\反馈评分。\ }
public void process() {
this.takeNumber(); this.transact(); this.evaluate(); } }
public class Client { public static void main(String a[]) { BankTemplateMethod bank; bank=(BankTemplateMethod)XMLUtil.getBean(); bank.process(); System.out.println(\--------------\ } }
public class Deposit extends BankTemplateMethod { public void transact() { System.out.println(\存款\ } }
public class Transfer extends BankTemplateMethod { public void transact() { System.out.println(\转账\ } }
public class Withdraw extends BankTemplateMethod { public void transact() { System.out.println(\取款\ } }
享元模式
实例一:共享网络设备(无外部状态) 很多网络设备都是支持共享的,如交换机、集线器等,多台终端计算机可以连接同一台网络设备,并通过该网络设备进行数据转发,如图所示,现用享元模式模拟共享网络设备的设计原理。 public class Client { public static void main(String args[]) { NetworkDevice nd1,nd2,nd3,nd4,nd5; DeviceFactory df=new DeviceFactory(); nd1=df.getNetworkDevice(\ nd1.use(); nd2=df.getNetworkDevice(\ nd2.use(); nd3=df.getNetworkDevice(\ nd3.use(); nd4=df.getNetworkDevice(\ nd4.use(); nd5=df.getNetworkDevice(\ nd5.use(); System.out.println(\df.getTotalDevice()); System.out.println(\+ df.getTotalTerminal()); } }
import java.util.*;
public class DeviceFactory { private ArrayList devices = new
ArrayList();
private int totalTerminal=0; public DeviceFactory() { NetworkDevice nd1=new Switch(\ devices.add(nd1); NetworkDevice nd2=new Hub(\ devices.add(nd2); } public NetworkDevice getNetworkDevice(String type) { if(type.equalsIgnoreCase(\ { totalTerminal++; return
(NetworkDevice)devices.get(0); } else if(type.equalsIgnoreCase(\ { totalTerminal++; return
(NetworkDevice)devices.get(1); } else { return null; } } public int getTotalDevice() { return devices.size(); } public int getTotalTerminal() { return totalTerminal; } }
public class Hub implements NetworkDevice { private String type; public Hub(String type) { this.type=type; } public String getType() { return this.type; } public void use() { System.out.println(\by Hub, type is \ } }
public interface NetworkDevice { public String getType(); public void use(); }
public class Switch implements NetworkDevice { private String type; public Switch(String type) { this.type=type; } public String getType() { return this.type; } public void use() { System.out.println(\by switch, type is \
}
}
相关推荐: