模板模式:定义一个操作的骨架。把一些其它操作延迟到子类中(例子:servlet中sevkce方法中定义了[doPost(),doGet(),doPut(),doDelete(),doTrace(),doHead()])
比如:
/**
* An abstract class which can get content from a file or a HTTP URL
* or other resource
*/
public abstract class AbstractRead {
protected String resource;
public void getContent() { // Template Method
if(open()) {
readContent();
close();
}
}
public void setResource(String s) {
resource = s;
}
protected abstract boolean open();
protected abstract void readContent();
protected abstract void close();
//定义一个算法的骨架。把一些操作在子类中
}
/**
* A concrete class extends AbstractRead
* This class can read from a file
*/
import java.io.*;
public class ReadFile extends AbstractRead {
private BufferedReader in = null;
public ReadFile() {
}
public ReadFile(String fileName) {
resource = fileName;
}
protected boolean open() {
try {
in = new BufferedReader(new FileReader(resource));
} catch(IOException e) {
System.out.println("Can not open file!");
return false;
}
return true;
}
protected void readContent() {
try {
if(in != null) {
String str;
while((str = in.readLine()) != null) {
System.out.println(str);
}
}
} catch(IOException e) {
System.out.println("Read file error !");
}
}
protected void close() {
if(in != null) {
try {
in.close();
} catch(IOException e) {
System.out.println("IO error !");
}
}
}
}
/**
* A concrete class extends AbstractRead
* This class can read HTML from a HTTP URL
*/
import java.io.*;
import java.net.*;
public class ReadHtml extends AbstractRead {
private URLConnection conn;
private BufferedReader in;
public ReadHtml() {
}
public ReadHtml(String s) {
resource = s;
}
public boolean open() {
try {
URL url = new URL(resource);
conn = url.openConnection();
in = new BufferedReader (
new InputStreamReader(conn.getInputStream()));
} catch (MalformedURLException e) {
System.out.println("Uable to connect URL:" + resource);
return false;
} catch (IOException e) {
System.out.println("IOExeption when connecting to URL" + resource);
return false;
}
return true;
}
protected void readContent() {
try {
if(in != null) {
String str;
while((str = in.readLine()) != null) {
System.out.println(str);
}
}
} catch(IOException e) {
System.out.println("Read file error !");
}
}
protected void close() {
if(in != null) {
try {
in.close();
} catch(IOException e) {
System.out.println("IO error !");
}
}
}
}
/**
* A test client
*/
public class Test {
public static void main(String[] args) {
// You should change the path of "test.txt" in your local machine
String fileName = "d://test.txt";
String url = "http://www.sina.com.cn";
AbstractRead fileRead = new ReadFile();
AbstractRead htmlRead = new ReadHtml();
fileRead.setResource(fileName);
htmlRead.setResource(url);
System.out.println("----- Read from a file -----");
fileRead.getContent();
System.out.println("----- Read from a url -----");
htmlRead.getContent();
}
}