继续上一篇
装饰模式
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活
Component是定义一个对象接口,可以给这些对象动态地添加职责
ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责
Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的
ConcreteDecorator就是具体的装饰对象,起到Component添加职责的功能
Component类
public abstract class Component {
public abstract void Operaion();
}
ConcreteComponent类
public class ConcreteComponent extends Component {
@Override
public void Operaion() {
// TODO Auto-generated method stub
System.out.println("具体对象的操作");
}
}
Decorator类
public abstract class Decorator extends Component {
protected Component component;
//设置Component
public void SetComponent(Component component){
this.component=component;
}
//重写Operation(),实际执行的是Component的Operation()
public void Operation(){
if(component!=null){
component.Operaion();
}
}
}
ConcreteDecoratorA类
public class ConcreteDecoratorA extends Decorator {
//本类的独有功能,以区别于ConcreteDecoratorB
private String addedState;
@Override
public void Operaion() {
// TODO Auto-generated method stub
super.Operation();
addedState="new State";
System.out.println("具体装饰对象A的操作");
}
}
ConcreteDecoratorB类
public class ConcreteDecoratorB extends Decorator {
@Override
public void Operaion() {
// TODO Auto-generated method stub
super.Operation();
AddedBehavior();
System.out.println("具体装饰对象B的操作");
}
//本类的独有的方法,以区别于ConcreteDecoratorA
private void AddedBehavior(){
}
}
当需要在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂
而装饰模式却提供了很好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象。
代理模式
为其他对象提供一种代理以控制对这个对象的访问
Subject 类
public abstract class Subject {
public abstract void Request();
}
RealSubject类
public class RealSubject extends Subject {
@Override
public void Request() {
// TODO Auto-generated method stub
System.out.println("真实的请求");
}
}
Proxy类
public class Proxy extends Subject {
RealSubject realSubject;
@Override
public void Request() {
// TODO Auto-generated method stub
if(realSubject==null){
realSubject=new RealSubject();
}
realSubject.Request();
}
}
客户端
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Proxy proxy=new Proxy();
proxy.Request();
}
}
适应场景
第一. 远程代理,也就是为一个对象在不同的地址空间提供局部代表,这样可以隐藏一个对象存在于不同地址空间的事实
第二. 虚拟代理,是根据需要创建开销很大的对象,通过它来存放实例化需要很长时间的真实对象
第三. 安全代理,用来控制真实对象访问时的权限
第四. 智能指引,是指调用真实的对象时,代理处理另外一些事