黑马程序员---装饰类设计模式

来源:互联网 发布:win7 telnet 端口23 编辑:程序博客网 时间:2024/04/30 22:47
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------


装饰模式比继承要灵活,避免了集成体系的臃肿
而且降低了类与类之间的关系

装饰类因为增强已有对象,具备的功能和已有的对象是相同的,
只不过提供了更强的功能,所以装饰类和被装饰类都是属于一个体系中。

BufferedInputStreamm也是一个装饰类,下面是我自定义的一个BufferedInputStreamm类,

把read()方法按照我们的想法实现出来

class  MyBufferedInputStreamm{private InputStream in;//将InputStream对象传给装饰类MyBufferedInputStreamm(InputStream in){this.in = in;}private int pos = 0;//定义一个指针,private int count = 0;//定义一个计数器private byte[] buf = new byte[1024];//定义一个字节数组public int myRead()throws IOException{if (count==0)//判断计数器为零时,数组中没有数据,需要往里面存储{count = in.read(buf);if (count<0){return -1;}pos = 0;byte b = buf[pos];pos++;count--;return b&255;}else if (count>0)//判断数组中有对象,然后取出来,//同时指针指向下一个数据,计数器减一,表示数据减少一个{byte b = buf[pos];pos++;count--;return b&255;}return -1;}public void myClose()throws IOException{in.close();}}


0 0