(七)装饰器模式 Decorator
装饰器模式是为了动态的给一个对象增加一些新功能。装饰对象与被装饰的对象需要实现同一个接口,装饰对象持有被装饰对象的实例。
interface DecoratorSourceable{
public void method();
}
//被装饰类
class DecoratorSource implements DecoratorSourceable{
public void method(){
System.out.println("Source");
}
}
//装饰类
class Decorator implements DecoratorSourceable{
private DecoratorSourceable source;//这里是持有被装饰类,但是写为接口
public Decorator(DecoratorSourceable source){
this.source = source;
}
public void method(){
System.out.println("before");
source.method();
System.out.println("after");
}
}
public class DecoratorTest {
public static void main(String[] args) {
DecoratorSourceable source = new DecoratorSource();
DecoratorSourceable decorator = new Decorator(source);
decorator.method();
}
}
需要扩展一个类的功能,或者想动态的为一个对象增加功能,还能动态的取消。可0以考虑用装饰模式。继承是静态的,不能动态增加或者删除。
借助装饰器模式,可以混合操作的不同变化。经典的实例是输入输出流,可以从其他流组合成一个新的流。装饰器模式还可以用来建立函数包装器,能根据有限的函数类集合创建大量的函数 对象。此外,借助装饰器模式可以灵活设计具有公共操作的类,这些公共操作往往具有不同的实现方式。这样就可以再运行时集成新的混合的变化。
(八)代理模式
普通对象可以通过公共接口完成自己需要完成的工作,然后有些对象却由于某些原因无法履行自己的日常的职责。例如有的对象加载时间过长,有的对象运行在其他计算机上面,或者需要拦截发送到对象的消息等。对于这些场景,我们可以引入代理对象,通过它承担客户端需要的职责,并将响应的请求转发给底层的目标对象。
interface ProxySourceable{
public void method();
}
class ProxySource implements ProxySourceable {
public void method(){
System.out.println("Proxy method");
}
}
class Proxy implements ProxySourceable{
private ProxySource source;
public Proxy(){
super();
this.source = new ProxySource();
}
public void method(){
before();//可以添加新方法控制,或统计
source.method();
after();//可以修改结果
}
private void after(){
System.out.println("after");
}
private void before(){
System.out.println("before");
}
}
public class ProxyTest{
public static void main(String[] args){
ProxySourceable source = new Proxy();
source.method();
}
}
使用场景:
已有方法使用时候需要对原有方法改进,直接修改原有方法违反了“对扩展开放,对修改关闭”原则。采用代理类调用原来方法可以清晰地划分功能,有助于后期维护。