设计模式说起来我们可能会很陌生,但是我们基本上都使用过,只是我们不知道罢了,比如说使用 BufferedOutputStream 输出的时候,里面得传入 FileOutputStram ,实际上就是装饰设计模式,就是对 FIleOutputStram 进行了装饰,功能加强了
这里我们来说说 静态代理设计模式
比如说我们要租房子,自己去找太麻烦,就直接给中介来帮我们找,这样可以很方便
首先来一个租房接口,里面就放一个方法,叫做租房
/**
* 租房
* @author snow
*
*/
public interface Renting {
/**
* 租房子
*/
public void retingHouse();
}
然后来一个客户类,也就是我自己,实现租房接口,说出我的需求
/**
* 我在租房子
* @author snow
*
*/
public class Custom implements Renting {
@Override
public void retingHouse() {
System.out.println( "给我租个大别墅,带游泳池的。" );
}
}
再来一个房屋中介,帮我忙前忙后
/**
* 中介,房屋中介
* @author snow
*
*/
public class IntermediaryHouse implements Renting {
/**
* 客户
*/
private Renting custom;
public IntermediaryHouse(Renting custom) {
this.custom = custom;
}
private void before() {
System.out.println("客户来了,赶快找房....");
}
private void after() {
System.out.println("房找好了,赶快帮客户打扫房屋,好让客户尽快入住...");
}
@Override
public void retingHouse() {
before();
// 真正租房的还是我自己
custom.retingHouse();
after();
}
}
然后运行代码实例:
// 创建客户
Custom custom = new Custom();
// 创建中介
IntermediaryHouse intermediaryHouse = new IntermediaryHouse(custom);
intermediaryHouse.retingHouse();
运行结果: