首页 > 试题广场 >

论坛权限控制设计:在一个论坛中已注册用户和游客的权限不同,已

[单选题]
论坛权限控制设计:在一个论坛中已注册用户和游客的权限不同,已注册的用户拥有发帖、修改自己的注册信息、修改自己的帖子等功能;而游客只能看到别人发的帖子,没有其他权限。使用( )来设计该权限管理模块。
  • 工厂方法模式
  • 代理模式 
  • 享元模式  
  • 外观模式
为什么这里使用代理模式,我的想法是:这里需要对发帖、修改信息等进行权限管理,类似于Spring中的AOP加强,所以可以使用代理模式创建一个代理对象,由代理对象对操作人员进行权限校验,如果不满足权限,直接不让其进行操作。
发表于 2023-03-19 21:26:03 回复(0)
代理模式,给某一个对象提供一个代理对象,并由代理对象控制原对象的引用,属于结构类型模式,创建现有对象的对象,向具有代理对象提供功能性接口,相当于我们生活中的中介
发表于 2022-04-08 09:33:25 回复(0)
public interface Forum {
    public void viewPosts();
}

// 用户类:实现用户的方法
public class User implements Forum {
    public void viewPosts() {
        System.out.println("Viewing all posts");
    }
    public void createPost() {
        System.out.println("Creating a new post");
    }
    public void editPost() {
        System.out.println("Editing an existing post");
    }
    public void editProfile() {
        System.out.println("Editing user profile");
    }
}

// 代理类:控制用户和游客的权限
public class ForumProxy implements Forum {
    private User user;

    public ForumProxy(User user) {
        this.user = user;
    }

    public void viewPosts() {
        user.viewPosts();
    }

    public void createPost() {
        if (user != null) {
            user.createPost();
        } else {
            System.out.println("Guests cannot create posts");
        }
    }

    public void editPost() {
        if (user != null) {
            user.editPost();
        } else {
            System.out.println("Guests cannot edit posts");
        }
    }

    public void editProfile() {
        if (user != null) {
            user.editProfile();
        } else {
            System.out.println("Guests cannot edit profiles");
        }
    }
}

// 测试代码
public class Test {
    public static void main(String[] args) {
        User user = new User();
        ForumProxy forum = new ForumProxy(user);

        forum.viewPosts(); // View all posts
        forum.createPost(); // Create a new post
        forum.editPost(); // Edit an existing post
        forum.editProfile(); // Edit user profile

        ForumProxy guestForum = new ForumProxy(null);
        guestForum.viewPosts(); // View all posts
        guestForum.createPost(); // Guests cannot create posts
        guestForum.editPost(); // Guests cannot edit posts
        guestForum.editProfile(); // Guests cannot edit profiles
    }
}
发表于 2023-06-17 21:52:04 回复(0)