黑马程序员技术交流社区
标题:
为什么要对装饰类横加无理的约束?
[打印本页]
作者:
李大强
时间:
2013-2-11 18:26
标题:
为什么要对装饰类横加无理的约束?
在装饰设计模式中,为什么装饰类和被装饰类都必须所属同一个接口或者父类?
直接定义一个Buffer类来接收一个特定的输入流或输出流,然后再自定义一个缓冲区对流中的数据进行缓冲不就行了,
何必非要属于同一个接口或者父类呢?
我想象中的缓冲类如下:
class BufferWriter//此类跟本就没必要和被装饰类属于同一个接口或者父类!
{
BufferWriter(Wirter w)
{
}
}
class BufferWriter extends Writer //此类为什么非要和被装饰类属于同一个接口或者父类呢?
{
BufferWriter(Writer w)
{
}
}
作者:
周怡
时间:
2013-2-11 20:37
本帖最后由 周怡 于 2013-2-11 20:40 编辑
这个就是装饰模式嘛,你看下
public class BufferedWriter extends Writer {
//装饰模式
private Writer out;
}
//构造函数
public BufferedWriter(Writer out, int sz) {
super(out);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.out = out;
cb = new char[sz];
nChars = sz;
nextChar = 0;
//获取换行的符号\n \r,和方法System.getProperty("line.separator")一样
lineSeparator = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("line.separator"));
}
//write有关
public void write(int c) throws IOException {
synchronized (lock) {
//判断是否有输出流
ensureOpen();
//如果缓存数组写满了,就flush数组。
if (nextChar >= nChars)
flushBuffer();
//将内容写入缓存数组中
cb[nextChar++] = (char) c;
}
}
//flush,这个方法就知道flush的重要性,
void flushBuffer() throws IOException {
synchronized (lock) {
ensureOpen();
if (nextChar == 0)
return;
//将数据写入流
out.write(cb, 0, nextChar);
nextChar = 0;
}
}
public void write(String s, int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
int b = off, t = off + len;
while (b < t) {
int d = min(nChars - nextChar, t - b);
//将字符串转为字符数组
s.getChars(b, b + d, cb, nextChar);
//写入缓存数组
b += d;
nextChar += d;
if (nextChar >= nChars)
//如果写满了,就写入流中。
flushBuffer();
}
}
}
//writeLine 写一个换行
public void newLine() throws IOException {
//同样写到缓存数组里
write(lineSeparator);
}
//flush
public void flush() throws IOException {
synchronized (lock) {
flushBuffer();
out.flush();
}
}
//关闭资源
public void close() throws IOException {
synchronized (lock) {
if (out == null) {
return;
}
try {
//最后还释放了一次。不过没有执行flush方法,所以在close前还是要执行一次flush!
flushBuffer();
} finally {
out.close();
out = null;
cb = null;
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2