c++ - 代理模式 - 适用性和示例

标签 c++ oop design-patterns proxy-classes

来自这里:http://www.oodesign.com/proxy-pattern.html

Applicability & Examples

The Proxy design pattern is applicable when there is a need to control access to an Object, as well as when there is a need for a sophisticated reference to an Object. Common Situations where the proxy pattern is applicable are:

Virtual Proxies: delaying the creation and initialization of expensive objects until needed, where the objects are created on demand (For example creating the RealSubject object only when the doSomething method is invoked).

Protection Proxies: where a proxy controls access to RealSubject methods, by giving access to some objects while denying access to others.

Smart References: providing a sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand.

那么,Virtual Proxies 不能通过为新对象创建单独的函数(构造函数除外)来创建吗?

Protection Proxies 不能通过简单地将函数设为私有(private)并只让派生类获得访问权限来创建吗?或者通过 friend 类?

Smart References 不能由统计创建对象数量的静态成员变量创建吗?

在哪些情况下应该在访问说明符和继承上首选 Proxy 方法?

我错过了什么?

最佳答案

你的问题有点抽象,我不确定我能否很好地回答,但这是我对每个问题的看法。就我个人而言,我不同意其中一些东西是工作的最佳设计,但这不是你的问题,而是一个意见问题。

虚拟代理 我根本不明白你想在这里说什么。这里模式的要点是,您可能有一个您知道将占用 100MB 的对象 A,但您不确定是否需要使用该对象。

为了避免在需要时为该对象分配内存,您创建了一个虚拟对象 B,它实现了与 A 相同的接口(interface),并且如果它的任何方法被调用,B 将创建 A 的实例,从而避免分配内存直到它被调用需要。

保护代理 在这里我认为你误解了模式的使用。这个想法是能够动态地控制对对象的访问。例如,您可能希望 A 类能够访问 B 类的方法,除非条件 C 为真。我相信您可以看到,这无法通过使用访问说明符来实现。

智能引用 在这里,我认为您误解了对智能指针的需求。由于这是一个相当复杂的话题,我将简单地提供一个关于它们的问题的链接:RAII and smart pointers in C++

如果您从未使用过像 C 这样您自己管理内存的语言进行编程,那么这可能解释了困惑。

我希望这有助于回答您的一些问题。

编辑:

我没有注意到它被标记为 c++,所以我假设您确实认识到需要清理动态内存。只有当您只打算拥有对象的一个​​实例时,单个静态引用计数才会起作用。如果您创建了一个对象的 2000 个实例,然后删除了其中的 1999 个实例,那么在最后一个离开范围之前,它们都不会释放内存,这显然是不可取的(假设您已经跟踪了所有已分配内存的位置为了能够释放它!)。

编辑 2:

假设你有一个类如下:

class A {
public:  
  static int refcount;

  int* allocated_memory;

  A() { 
    ++refcount;
    allocated_memory = new int[100000000];
  }

  ~A() { 
    if(! --refcount) {
      delete [] allocated_memory;
    }
  }
}

以及一些使用它的代码:

int main() {
  A problem_child;  // After this line refcount == 1
  while(true) {
    A in_scope;     // Here refcount == 2

  }                 // We leave scope and refcount == 1. 
                    // NOTE: in_scope.allocated_memory is not deleted
                    //       and we now have no pointer to it. Leak!
  return;
} 

正如您在代码中看到的,refcount 计算对所有对象的所有引用,这会导致内存泄漏。如果您需要,我可以进一步解释,但这本身就是一个单独的问题。

关于c++ - 代理模式 - 适用性和示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9664304/

相关文章:

php - 从不在构造函数中实例化对象?

c# - 为什么抽象类的构造函数应该被保护,而不是公共(public)的?

JavaScript 设计模式 : What is a Concrete Factory?

C++类指针成员行为奇怪(错误)

c++ - 与/usr/bin/openssl 输出相同的 C/C++ 程序

c++ - 连接pthreadgc2.dll到qt项目

java - 提取特定行java

c++ - 引用 C++ UWP 项目

python - "None"尝试在 Python 中返回 dict 的值时给出

java - 需要一些有关包装类模式的帮助