您的位置:首页 > 编程语言 > Java开发

Java设计模式(11) —— 原型

2009-08-27 20:56 417 查看
Prototype

Intent

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

How to

Prototype Manager

register prototypes

Prototype

declares an interface for cloning itself.

ConcretePrototype

implements an operation for cloning itself.

Known cases

Game Components

Authorization System

UML



示例:

系统一般有普通用户和高级用户,他们分别有不同的权限。如果权限设置放在文件中,每次新建用户时,都要读文件,这会造成系统的负担。因为大多数用户只有名字等其他信息不同而已,权限基本是相同的,可以运用上述模式。

代码:

public class UserManager {
private static UserManager unique = null;
static {
String[] commonAuth = null; //从配置文件或其他地方得到
String[] advanceAuth = null;
User common = new User(commonAuth);
User advance = new User(advanceAuth);
unique = new UserManager(common, advance);
}

public static UserManager getInstance() {
return unique;
}

private User common;
private User advance;

private UserManager(User common, User advance) {
this.common = common;
this.advance = advance;
}

public User getCommonUser() {
return common.clone();
}

public User getAdvanceUser() {
return advance.clone();
}

}


public class User implements Cloneable {
private List<String> authList;
private String name;

public User(String[] auths) {
authList = new ArrayList<String>();
for (int i = 0; i < auths.length; i++) {
authList.add(auths[i]);
}
}

public User clone() {
User user = new User(this.getAuths());
return user;
}
public void addAuth(String auth) {
authList.add(auth);
}
public String[] getAuths() {
String[] auths = new String[authList.size()];
for (int i = 0; i < authList.size(); i++) {
auths[i] = authList.get(i);
}
return auths;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}
}


注意:一般PrototypeManager是单例
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: