今天学习Proxy模式。代理模式是在对已有对象操作困难或者不太方便时,选择用代理的方式对对象进行访问。Proxy实现的方法必须和被代理对象一致。
举一个简单的例子, 有一个Math类实现了IMath接口
package com.proxy;
public interface IMath {
public int add(int a, int b);
public int sub(int a, int b);
public int mul(int a, int b);
public int dev(int a, int b);
}
package com.proxy;
public class Math implements IMath {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public int sub(int a, int b) {
return a - b;
}
@Override
public int mul(int a, int b) {
return a * b;
}
@Override
public int dev(int a, int b) {
return a / b;
}
}
如果测试的话
package com.proxy;
import static org.junit.Assert.*;
import org.junit.Test;
public class Client {
@Test
public void test() {
Math math = new Math();
int a = 2;
int b = 1;
assertEquals(3, math.add(a, b));
assertEquals(1, math.sub(a, b));
assertEquals(2, math.mul(a, b));
assertEquals(2, math.dev(a, b));
}
}
如果有个代理类ProxyMath代理Math类。先写测试类
package com.proxy;
import static org.junit.Assert.*;
import org.junit.Test;
public class Client {
@Test
public void test() {
ProxyMath proxy = new ProxyMath();
int a = 2;
int b = 1;
assertEquals(3, proxy.add(a, b));
assertEquals(1, proxy.sub(a, b));
assertEquals(2, proxy.mul(a, b));
assertEquals(2, proxy.dev(a, b));
}
}
ProxyMath类同于继承IMath接口
package com.proxy;
public class ProxyMath implements IMath {
private Math math;
public ProxyMath() {
math = new Math();
}
@Override
public int add(int a, int b) {
return math.add(a, b);
}
@Override
public int sub(int a, int b) {
return math.sub(a, b);
}
@Override
public int mul(int a, int b) {
return math.mul(a, b);
}
@Override
public int dev(int a, int b) {
return math.dev(a, b);
}
}