decorated with design patterns

Decorator Design Pattern Definition: Dynamically attach responsibilities to objects, to extend functionality, decorators provide a more flexible alternative to inheritance.

Decorator features:
     1. The decorator and the decorator have the same supertype.

     2. Inject the decorated object through the constructor.

     3. The decorator can add its own behavior before and after the method being called by the decorator. This is somewhat similar to a static proxy.


In fact, the decorator design pattern is a method of enhancing classes with composition. Java io classes are heavily applied to the decorator pattern.

Code:

   
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyFileInputStream extends FilterInputStream{

	protected MyFileInputStream(InputStream in) {
		super(in);
	}

	@Override
	public int read() throws IOException {
		int i = super.read();
		return i==-1?i:Character.toLowerCase((char)i);
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		int re = super.read(b, off, len);
		for(int i=off;i<re+off;i++){
			b[i] = (byte) Character.toLowerCase((char)b[i]);
		}
		return re;
	}
	
}


  

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326680123&siteId=291194637