设计模式之装饰模式

<!--同样这只是我个人的学习笔记,如写的不好请大家理解,我也是从老师和网上学来的.>decorator模式在AWT,Swing,和流中比较常见,eg.用缓冲流来包装低级流,用高级流再来包装缓冲流.其典型的代码如下:

FileWriter fw = new FileWrite("mydata.txt");
BufferedWriter buff = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(buff);
out.print(".......");

按照这个理解先给大家取个简单的例子


package decorator;

public interface {
public void 倒水();
}

package decorator;

public class 水壶 implements {

public void 倒水() {
                 //没加工
            System.out.println("");
}

}

package decorator;

public class 热水壶 implements {
private h;

public 热水壶( h){
this.h = h;
}

public void 倒水() {
                  //经过加热处理
System.out.print("加热");
h.倒水();
}

}

package decorator;

public class 咖啡壶 implements {
private h;

public 咖啡壶( h){
this.h = h;
}

public void 倒水() {
                  //换了咖啡
System.out.print("加咖啡");
h.倒水();
}

}
//....看到这大家也有点心理有数了吧,同样可以在写几个加牛奶,加果汁的壶,你想装什么,倒出来的就经过包装过的,我想这就是装饰模式的思想所在.

package decorator;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
水壶 h = new 水壶();

热水壶 hot = new 热水壶(h);
// hot.倒水();

咖啡壶 ch = new 咖啡壶(hot);
ch.倒水();
}

}

//接一下写个比较更程序性的例子 由于明天要去面试,所以接下来的代码我不做过多的颜色处理,以后有空修改.另外本代码需要Log4j jar包和属性文件我都在附件中

package decorator.simple;

public interface IMyLogger {
public abstract void print(String msg);
}

package decorator.simple;

import org.apache.log4j.Logger;

//封装Log4j,自定义一个简单的输出信息方法
public class MyLogger implements IMyLogger{
private Logger log = Logger.getLogger(this.getClass());

public void print(String msg){
log.info(msg);
}

}

//再包装,对输出信息进行加密

package decorator.simple;

public class EncriptLogger implements IMyLogger{
private IMyLogger logger;
public EncriptLogger(IMyLogger logger){
this.logger = logger;
}

public void print(String msg) {
msg = encript(msg);
logger.print(msg);
}

public String encript(String s){
StringBuffer sb = new StringBuffer();
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
c = (char)(c^10);
sb.append(c);
}
return sb.toString();
}

//以HTML格式输出信息

package decorator.simple;

public class HtmlLogger implements IMyLogger{
private IMyLogger logger;
public HtmlLogger(IMyLogger logger){
this.logger = logger;
}

public void print(String msg) {
msg = htmlString(msg);
logger.print(msg);
}

public String htmlString(String msg){
StringBuffer sb = new StringBuffer();
sb.append("<html>");
sb.append("<body>");
sb.append("<font color=red>");
sb.append(msg);
sb.append("</font>");
sb.append("</body>");
sb.append("</html>");
return sb.toString();
}
}

//测试类

package decorator.simple;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
MyLogger log = new MyLogger();
HtmlLogger htmlLogger = new HtmlLogger(log);
EncriptLogger encriptLogger = new EncriptLogger(htmlLogger);
encriptLogger.print("你好");
}

}






个人总结:通过这2个例子,我对Decorator模式有了稍微的了解,无非是定义一个总接口,然后有此衍生出来的类都实现这个接口,在类中都定义一个带有此接口类型的构造方法.

你可能感兴趣的:(apache,设计模式,log4j,面试,swing)