1、类图
2、代码
2.1 Person.java
package test14;
/*
* 抽象权限类
*/
public interface Person {
public void modifyUserInfo();
public void viewPerson();
public void publishSelf();
public void modifyNote();
public void setAge(int age);
}
2.2 PermissionProxy.java
package test14;
public class PermissionProxy implements Person{
private RealPermission permission = new RealPermission();
private int age = 20;
public void modifyUserInfo() {
permission.modifyUserInfo();
if(age<18) {
System.out.println("对不起,不能早恋!");
System.out.println("正在退出服务...。");
}else {
System.out.println(" 正在修改您的个人信息....");
}
}
public void viewPerson() {
permission.viewPerson();
if(age<18) {
System.out.println("对不起,不能早恋!");
System.out.println("正在退出服务....");
}else {
System.out.println(" 正在浏览他人信息....");
}
}
public void publishSelf() {
permission.publishSelf(); //发布个人信息
if(age<18) {
System.out.println("对不起,不能早恋!");
System.out.println("正在退出服务....");
}else {
System.out.println(" 正在发布您的个人信息....");
}
}
public void modifyNote() {
permission.modifyNote();
if(age<18) {
System.out.println("对不起,不能早恋!");
System.out.println("正在退出服务....");
}else {
System.out.println(" 正在修改您发布的个人信息....");
}
}
public void setAge(int age) {
this.age = age;
}
}
2.3 RealPermission.java
package test14;
/*
* 真实权限类
*/
public class RealPermission implements Person{
public void modifyUserInfo() {
System.out.println("[修改个人信息]");
};
public void viewPerson() {
System.out.println("[浏览他人信息]");
};
public void publishSelf() {
System.out.println("[发布个人信息]");
};
public void modifyNote() {
System.out.println("[修改发布内容]");
};
public void setAge(int age) {
};
}
2.4 XMLUtil.java
package test14;
/*
* 读取XML文件并根据存储在XML文件中的类名获取对应的对象
*/
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.File;
public class XMLUtil {
@SuppressWarnings("deprecation")
public static Object getBean() {
try {
//创建DOM文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("src/test14/config.xml"));
//获取包含类名的文本节点
NodeList nl = doc.getElementsByTagName("className");
Node classNode = nl.item(0).getFirstChild();
String cName = classNode.getNodeValue();
//通过类名生成实例对象返回
Class<?> c = Class.forName("test14."+cName);
Object obj = c.newInstance();
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
2.5 config.xml
<?xml version="1.0"?>
<config>
<className>PermissionProxy</className>
</config>
2.6 Client.java
package test14;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person permission;
permission = (Person)XMLUtil.getBean();
permission.modifyUserInfo();
permission.viewPerson();
permission.publishSelf();
permission.modifyNote();
System.out.println("------- 修改年龄后-----------");
permission.setAge(15); /*把年龄设置为未成年*/
permission.modifyUserInfo();
permission.viewPerson();
permission.publishSelf();
permission.modifyNote();
}
}
3、运行截图