抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

在代理模式(Proxy Pattern)中,一个类代表另一个类的功能。这种类型的设计模式属于结构型模式。

意图:为其他对象提供一种代理以控制对这个对象的访问。

主要解决:在直接访问对象时带来的问题,比如说:要访问的对象在远程的机器上。在面向对象系统中,有些对象由于某些原因(比如对象创建开销很大,或者某些操作需要安全控制,或者需要进程外的访问),直接访问会给使用者或者系统结构带来很多麻烦,我们可以在访问此对象时加上一个对此对象的访问层。

何时使用:想在访问一个类时做一些控制。

实例

创建一个动作(action)接口,自定义其实现,并为这个实现添加代理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public interface Action {
void doAction();
}

public class UserAction implements Action {
@Override
public void doAction() {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "*" + i + "=" + i * j + " ");
}
System.out.println();
}
}
}

public class ProxyAction implements Action {
private UserAction userAction;

public ProxyAction(UserAction userAction) {
this.userAction = userAction;
}

@Override
public void doAction() {
long startTime = System.currentTimeMillis();
userAction.doAction();//真正执行的业务
long endTime = System.currentTimeMillis();
System.out.println("执行时间" + (endTime-startTime));
}
}

public class ProxyTest {
public static void main(String[] args) {
Action action1 = new UserAction();
Action action2 = new ProxyAction((UserAction) action1);
action2.doAction();
}
}

模板模式

意图:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

主要解决:一些方法通用,却在每一个子类都重新写了这一方法。

何时使用:有一些通用的方法。

如何解决:将这些通用算法抽象出来。

关键代码:在抽象类实现,其他步骤在子类实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
abstract class BaseManger {
/**
* 验证权限
* @param name
* @param method
*/
public void action(String name,String method){
if ("admin".equals(name)){
execute(method);
}else {
System.out.println("无权限");
}
}
public abstract void execute(String method);
}

public class UserManger extends BaseManger{
public void execute(String method){
if ("add".equals(method)) {
System.out.println("添加");
}else if("del".equals(method)){
System.out.println("删除");
}
}
}

评论