Proxy - what code (and where) translates ProxyService into RealService calls? Why/when use this? Layers - how to implement? Memento - why not just persist state to a cache or file?
My understanding of the Proxy pattern is that you have some kind of Service
interface that has ProxyService
and RealService
concretions. For some reason, you can't access the RealService
, so you code against a ProxyService
instance and then let the framework link the proxy to the real instance of your service. Only two problems:
Service
and ProxyService
, but not RealService
- can someone provide examples as to when this could happen?How is this different from the Memento pattern? My understanding of Memento's definition is that it is used for saving an object state, which is what a Proxy is really doing, yes? If not please explain how Memento is different than Proxy! Thanks in advance!
First off, I'll caveat my answer by saying that I don't believe there are any hard and fast rules about patterns - you take what you need from them and nothing more. The way that I use certain patterns is undoubtedly different from how another developer might choose to use them. That said, here's my take on your question.
Proxy Pattern Explained
The way I know the Proxy
design pattern, you use it to do two things:
Maybe RealService
has a method doSomethingReallyDangerous()
that you want to hide. Or even more innocuous, maybe RealService
has several hundred methods that you don't need to see every time you type the .
after a RealService
instance's variable name. You'd use a proxy for any of this.
For further reading, this article has a lot of good information:
http://sourcemaking.com/design_patterns/proxy
Differences with Memento Pattern
The Memento
pattern allows you to roll back an object to its original state, or some previous state, by storing intermediate states alongside the concrete object. Sort of like an "undo" for programming. You'd probably use a Proxy
pattern to implement Memento
, but Proxy
doesn't guarantee saving of object state or rollback - it just lets you refer to the same object for method calls if instantiating that object over again is prohibitively expensive.
So hopefully that helps - I like to think of Memento
as a more full-featured version of Proxy
, but not all Proxy
implementations are Mementos
.