设计模式示例-适配器模式
来源:互联网 发布:js求最大公约数 编辑:程序博客网 时间:2024/05/17 19:57
package adapter;import java.io.IOException;/** * * 文件IO处理接口,target * * @author duchao * @version [版本号, 2012-10-16] * @see [相关类/方法] * @since [产品/模块版本] */public interface FileIO{ /** * 从指定文件路径读取文件 * @param fileName * @throws IOException * @see [类、类#方法、类#成员] */ public void readFromFile(String fileName) throws IOException; /** * 向指定文件路径写入文件 * @param fileName * @throws IOException * @see [类、类#方法、类#成员] */ public void writeToFile(String fileName) throws IOException; /** * 设置一个key-value键值对 * @param key * @param value * @see [类、类#方法、类#成员] */ public void setValue(String key, String value); /** * 获取对应key的value,没有则返回空字符串 * @param key * @return * @see [类、类#方法、类#成员] */ public String getValue(String key);}
package adapter;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;/** * * 相当于适配器模式中的适配器,继承已有的类Properties,实现了FileIO接口 * * @author Administrator * @version [版本号, 2012-10-17] * @see [相关类/方法] * @since [产品/模块版本] */public class FileProperties extends Properties implements FileIO{ @Override public String getValue(String key) { return getProperty(key, ""); } @Override public void readFromFile(String fileName) throws IOException { load(new FileInputStream(fileName)); } @Override public void setValue(String key, String value) { setProperty(key, value); } @Override public void writeToFile(String fileName) throws IOException { store(new FileOutputStream(fileName), "written by FileProperties"); } }
package adapter;import java.io.IOException;public class TestAdapter{ /** 测试适配器模式的主函数类 * @param args * @see [类、类#方法、类#成员] */ public static void main(String[] args) { FileIO fileIO = new FileProperties(); try { fileIO.readFromFile("c:/test.properties"); fileIO.setValue("year", "2012"); fileIO.setValue("month", "10"); fileIO.setValue("day", "17"); fileIO.writeToFile("c:/testNew.properties"); } catch (IOException e) { e.printStackTrace(); } } }