I'm building a php system with the Services/DAOs/Domain Models pattern, and now is the time to implement a caching system for the DAOs.

Would you use a decorator pattern, or maybe the strategy pattern?

What are the ups and downs of each one?

added requirement: Like I told in a comment answering to edalorzo I need to be able to use the DAOs without any caching at some moments. For the same method sometimes is acceptable to have cache, but some other times is not.

有帮助吗?

解决方案

I have seen the implementation of caches using a Proxy pattern. Particularly frameworks like AOP make use of proxies for most of these things.

According to the book Design Patterns and Elements of Reusable Object-Oriented Software the decorator and proxy pattern may look alike/

Page 216:

"Although decorators may have similar implementations as proxies, decorators have a different purpose. A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.

Proxies vary in the degree to which they are implemented like a decorator.A protection proxy might be implemented exactly like a decorator. On the other hand, a remote proxy will not contain a direct reference to its real subject but only an indirect reference, such as a "host ID and local address on the host". A virtual proxy will start off with an indirect reference such as a file name but will eventually obtain and use a direct reference"

It looks like your purpose with the cache is to avoid giving direct access to the real subject, so it sounds more like a proxy to me.

The comment above also clearly makes evident that an important difference between a proxy and a decorator is that the proxy may be responsible for instantiating or getting access to the real subject, whereas in the case of the decorator is kind of expected that such reference will be dynamically provided.

It would seem that the relationship between the proxy and real subject is more static than in the case of the decorator.

That being said, ultimately in you case is a matter of intent more than how the design will look like. At the end the solution is to have a wrapper object (either called Proxy or Decorator) that will intercept the method and allow you to control when to gain access to a cache or not depending on your cache policy.

其他提示

I've implemented it both ways in the past, and my experience has been that using a decorator results in a clearer separation of responsibilities between the two classes, as using a strategy requires support in the data access class, whereas with a decorator you write the data access class the same as you would if you weren't implementing cacheing.

许可以下: CC-BY-SA归因
scroll top