你的位置:首页 > ASP.net教程

[ASP.net教程]适配器模式的应用


1.适配源类:java.util.Properties

2.适配目标类:FileIO

3.适配器 FileProperties

 

package fileio;import java.io.IOException;public interface FileIO {  public void readFromFile(String fileName) throws IOException;    public void writeToFile(String fileName) throws IOException;    public void setValue(String key , String value);    public String getValue(String key);}

 

package fileio;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;public class FileProperties implements FileIO {      private Properties p;    public FileProperties(Properties p) {    this.p = p;  }    @Override  public void readFromFile(String fileName) throws IOException {    p.load(new FileInputStream(new File(fileName)));  }  @Override  public void writeToFile(String fileName) throws IOException {    p.store(new FileOutputStream(new File(fileName)), "");  }  @Override  public void setValue(String key, String value) {    p.setProperty(key, value);  }  @Override  public String getValue(String key) {    return p.getProperty(key);  }}

 

package fileio;import java.io.IOException;import java.util.Properties;public class Client {  public static void main(String[] args) {    FileIO fi = new FileProperties(new Properties());    try {      fi.readFromFile("test.txt");      fi.setValue("name", "tisa");      fi.setValue("age", "12");      fi.setValue("school", "CCNU");            fi.writeToFile("out.txt");    } catch (IOException e) {      e.printStackTrace();    }      }}