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:
- I can’t think of a single example when I would have access to
ServiceandProxyService, but notRealService– 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
Proxydesign pattern, you use it to do two things:Maybe
RealServicehas a methoddoSomethingReallyDangerous()that you want to hide. Or even more innocuous, maybeRealServicehas several hundred methods that you don’t need to see every time you type the.after aRealServiceinstance’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
Mementopattern 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 aProxypattern to implementMemento, butProxydoesn’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
Mementoas a more full-featured version ofProxy, but not allProxyimplementations areMementos.