KWIC:管道-过滤器模式.

来源:互联网 发布:模仿的软件 编辑:程序博客网 时间:2024/04/28 08:53

架构借鉴:http://blog.csdn.net/tobacco5648/article/details/8261758;

管道过滤器模式构成:filter虚类,pipe类,input类extends filter,output类 extends filter,shift 类extends filter;定义两个管道:一个负责连通input->shift,一个负责连通shift->output.

使用的方法和包:

1.ArrayLsit<String>:过滤器内部使用,过滤器之间使用Pipe;

2.PipedReader    :管道读数据类,you can use .read() to get the character in the pipe stream.the return value -1 means no more stream; 

int c=.read();

String line;

line+=(char)c;

3 PipedReader  :Pipe write data class.Use .write(char c) to put the c into the pipe stream.

.write(' ');

4..write.connnect(PipedReader obj): connect two sides of one pipe.which means,you can use .read() to get whatever you wirte via .write(); you can also ignore  maybe,but in risk;

5.shift():refer to my last blog;

6. close the pipe stream.

Main


public class Kwic3 {


public static void main(String[] args) {
try {
String filePath = "D:\\test.txt";
BufferedReader in = new BufferedReader(new FileReader(filePath));

Pipe in_trans=new Pipe();
Pipe out_trans=new Pipe();
InputFilter input=new InputFilter(in,in_trans);
ShiftFilter shift=new ShiftFilter(in_trans,out_trans);
Output output=new Output(out_trans);
System.out.println("before start");
input.start();
shift.start();
output.start();
input.stop();
shift.stop();
} catch (Exception e) {
System.err.print("wrong");
System.exit(1);
}

}
// BufferedReader in=new BufferedReader(new FileReader(filePath));


}


Pipe类&Filer


package Kwic3;


import java.io.IOException;


public abstract class Filter implements Runnable {
    protected Pipe input_;
    protected Pipe output_;
    private boolean isStarted=false;
    public  Filter(Pipe input,Pipe output){
    input_=input;
    output_=output;
    }
    public void start(){
    if(!isStarted)
    isStarted=true;
    Thread it=new Thread(this);
    it.start();
   
    }
    public void stop()
    {
    isStarted=false;
    }
    public void run(){
    try {
transform();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    protected abstract void transform() throws IOException;
}



package Kwic3;


import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;


public class Pipe {
   private PipedReader read_;
   private PipedWriter write_;
   public Pipe() throws IOException{
  write_=new PipedWriter();
  read_=new PipedReader();
  //write_.connect(read_);
  
   }
   public void write(int c) throws IOException{
 write_.write(c);
 
   }
  public int read() throws IOException{
return  read_.read();
  }
   
   public void closeWrite() throws IOException{
  write_.close();
   }
   public void closeRead() throws IOException{
  read_.close();
   }
}









0 0
原创粉丝点击