相关疑难解决方法(0)

这种面向密钥的访问保护模式是一种已知的习惯用法吗?

Matthieu M.在我之前看过的这个答案中提出了一种访问保护模式,但从未有意识地考虑过一种模式:

class SomeKey { 
    friend class Foo;
    SomeKey() {} 
    // possibly make it non-copyable too
};

class Bar {
public:
    void protectedMethod(SomeKey);
};
Run Code Online (Sandbox Code Playgroud)

这里只有一个friend关键类可以访问protectedMethod():

class Foo {
    void do_stuff(Bar& b) { 
        b.protectedMethod(SomeKey()); // fine, Foo is friend of SomeKey
    }
};

class Baz {
    void do_stuff(Bar& b) {
        b.protectedMethod(SomeKey()); // error, SomeKey::SomeKey() is private
    }
};
Run Code Online (Sandbox Code Playgroud)

它允许更多的细粒度访问控制不是制造Foo一个friendBar,避免了更复杂的代理模式.

有谁知道这种方法是否已经有一个名称,即,是一个已知的模式?

c++ design-patterns access-control friend

47
推荐指数
2
解决办法
8985
查看次数

我们能否增加这种面向密钥的访问保护模式的可重用性?

我们是否可以增加这种面向密钥的访问保护模式的可重用性:

class SomeKey { 
    friend class Foo;
    // more friends... ?
    SomeKey() {} 
    // possibly non-copyable too
};

class Bar {
public:
    void protectedMethod(SomeKey); // only friends of SomeKey have access
};
Run Code Online (Sandbox Code Playgroud)

为了避免持续的误解,这种模式不同于律师 - 客户的习惯用语:

  • 它可以比律师 - 客户更简洁(因为它不涉及通过第三类代理)
  • 它可以允许授权访问权限
  • ...但它对原始类也更具侵入性(每个方法一个虚拟参数)

(在这个问题中提出了一个侧面讨论,因此我打开了这个问题.)

c++ design-patterns idioms friend access-protection

26
推荐指数
1
解决办法
4417
查看次数