目录
什么是代理模式?
定义
代理模式(Proxy Pattern)是一种结构型设计模式,用于控制对一个真实对象的访问。它通过引入一个代理对象,为客户端提供间接访问真实对象的方式。代理对象拥有和真实对象相同的接口,这样客户端可以无感知地使用代理对象来完成对真实对象的操作。
(为其他对象提供一种代理以控制对这个对象的访问,举例形容一下:租房子时我们去找中介)
特点
代理模式通过引入一个代理对象来控制对原对象的访问。代理对象在客户端和目标对象之间充当中介,负责将客户端的请求转发给目标对象,同时可以在转发请求前后进行额外的处理。
代理一般可分三种:静态代理、动态代理和cglib动态代理
代理模式(java代码示例)
我仅用静态代理和动态代理展示一下:
1、静态代理
定义工厂类、代理类、测试类如下:
//工厂类
class Factory{
public void clothes(String size) {
System.out.println("为您只做了一件大小为"+size+"的衣服");
}
}
//代理类
class Proxy{
public Factory factory = new Factory();
public void clothes(String size) {
frontService();
factory.clothes(size);
endService();
}
public void frontService() {
System.out.println("售前服务");
}
public void endService() {
System.out.println("售后服务");
}
}
//测试类
public class ProTest {
public static void main(String[] args) {
Proxy proxy = new Proxy();
proxy.clothes("xl");
}
}
运行结果
2、动态代理
首先定义一个接口
public interface ByClothes {
void clothes(String size);
}
定义一个工厂类
public class ClotherFactory implements ByClothes {
public void clothes(String size) {
System.out.println("为您只做了一件大小为"+size+"的衣服");
}
}
定义一个代理类,实现接口
public class ClothesProxy implements ByClothes {
public ClotherFactory factory = new ClotherFactory();
public void clothes(String size) {
frontService();
factory.clothes(size);
endService();
}
public void frontService() {
System.out.println("售前服务");
}
public void endService() {
System.out.println("售后服务");
}
}
测试类:
public class Test {
public static void main(String[] args) {
ClothesProxy proxy = new ClothesProxy();
proxy.clothes("xxl");
}
}
运行结果:
代理模式的优缺点
优点:
职责分离:代理模式将访问控制与业务逻辑分离。
扩展性:可以灵活地添加额外的功能或控制。
智能化:可以智能地处理访问请求,如延迟加载、缓存等。
保护目标对象: 代理对象可以阻止客户端直接访问目标对象,从而保护目标对象不被滥用。
缺点:
性能开销:增加了代理层可能会影响请求的处理速度。
实现复杂性:某些类型的代理模式实现起来可能较为复杂。
应用场景
代理对象可以在访问真实对象之前或之后执行一些额外的操作,如缓存、安全验证、日志记录等。
通过使用虚拟代理,实现延迟加载,从而提高系统的性能。等等