这个不知道算是代理模式还是装饰者模式,不过本人认为更像是一个代理模式,继承了outputstream类,但是不用实现它的方法,而是另添加一个方法,可以直接写入一个对象
package io.proxy;
import java.io.Serializable;
public class User implements Serializable {
private String account;
private String password;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package io.proxy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.alibaba.fastjson.JSONObject;
public class FreshbinOutputStream extends OutputStream {
private FileOutputStream out;
public FreshbinOutputStream(String filePath) throws FileNotFoundException {
this.out = new FileOutputStream(filePath,true);
}
public void write(Object user) {
try {
String jsonstr = JSONObject.toJSONString(user);
out.write(jsonstr.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close(){
if(out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void write(int arg0) throws IOException {
// TODO Auto-generated method stub
}
}
package io.proxy;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Test {
public static void main(String[] args) {
User us1 = new User();
us1.setAccount("freshbin");
us1.setPassword("123");
FreshbinOutputStream fos = null;
try {
fos = new FreshbinOutputStream("h:/test/test.txt");
fos.write(us1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
fos.close();
}
}
}