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 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:
Restrict access to otherwise public methods of a particular object instance
Prevent otherwise-expensive, and unnecessary instantiation costs, by instantiating the concrete object on the first call to the proxy, then passing all further calls on the proxy through to the concrete instance your proxy created.
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.
Proxy is when someone is expecting a certain object, and you lie to him, and you say: Yes, here you have your object, but you are actually giving him something else...
Common uses for proxy:
To implement Lazy initialization: You are asked for an object representing the contents of a big file, or something which is very expensive to acquire, and you know that it's not needed at this right moment, or it might in fact never be used really. So you pass a proxy, that will only acquire the resource when it's 100% completely necessary (You can also start acquiring the resource anachronistically, and make the process using the proxy only start waiting when it really needs it). This is pretty common in ORMs. Also futures and promises implement something like this
To intercept calls:
You can pass a proxy which actually knows the real object, and intercept the calls that it gets, and do something interesting like logging them, changing some of them, etc...
There are also a lot of advanced and complex usages of the proxy, given that you often have the ability to determine the behavior at runtime. sorry for going out of Java, but in C#, Castle Proxy is used to implement mock objects for testing. You can also implement with a proxy things like chaining in underscore. And you can simulate a lot of "dynamic languages" features in static languages using proxies. You can also evaluate a piece of code with a proxy that actually logs every call that is made, and returns new proxies every time, to reconstruct the "original source code" by just executing it.
Memento pattern: is another thing completely. You use it when you want to work with an object, save it current state, counting doing thins with that object, and after a while you might want to choose to rollback to the previous state. You can use it to implement transactional behavior in your objects, when undoing the things by code is difficult. You can implement undo & redo functionality with this. (Instead of saving the change-delta, you save the full state). You can use it in simulations to start every time from the same point (You could say that a Source Version Server uses memento every once in a while [they generally use a combination of memento + delta changes]). A snapshot of a virtual machine or an hibernate of a computer is also a use of the memento pattern. And saving the state of something, so you can reproduce the exact same situation is also memento.
Related
I am working on a j2ee webapp divided in several modules. I have some metadata such as user name and preferences that I would like to access from everywhere in the app, and maybe also gather data similar to logging information but specific to a request and store it in those metadata so that I could optionally send it back as debug information to the user.
Aside from passing a generic context object throughout every method from the upper presentation classes to the downer daos or using AOP, the only solution that came in mind was using a threadlocal "Context" object very similar to a session BTW, and add a filter for binding it on ongoing request and unbinding it on response.
But such thing feels a little hacky since this breaks several patterns and could possibly make things complicated when it comes to testing and debugging so I wanted to ask if from your experience it is ok to proceed like this?
ThreadLocal is a hack to make up for bad design and/or architecture. It's a terrible practice:
It's a pool of one or more global variables and global variables in any language are bad practice (there's a whole set of problems associated with global variables - search it on the net)
It may lead to memory leaks, in any J2EE container than manages its threads, if you don't handle it well.
What's even worse practice is to use the ThreadLocal in the various layers.
Data communicated from one layer to another should be passed using Transfer Objects (a standard pattern).
It's hard to think of a good justification for using ThreadLocal. Perhaps if you need to communicate some values between 2 layers that have a third/middle layer between them, and you don't have the means to make changes to that middle layer. But if that's the case, I would look for a better middle layer.
In any case, if you store the values in one specific point in the code and retrieve it in another single point, then it may be excusable, otherwise you just never know what side affects any executing method may have on the values in the ThreadLocal.
Personally I prefer passing a context object, as the fact that the same thread is used for processing is an artifact of the implementation, and you shouldn't rely on such artifacts. The moment you want to use other threads, you'll hit a wall.
If those states are encapsulated in a Context object, I think that's clean enough.
When it comes to testing, the best tool is dependency injection. It allows to inject fake dependencies into the object under test.
And all dependency injection frameworks (Spring, CDI, Guice) have the concept of a scope (where request is one of these scopes). Under the hood, beans stored in the request scoped are indeed associated with a ThreadLocal variable, but this is all done by the dependency injection framework.
What I would do is thus to use a DI framework, which would make request-scope objects available anywhere, but without having to look them up, which would break testability. Just inject a request-scoped object where you want to use it, and the DI framework will retrieve it for you.
You must know that a servlet container can / will re-use threads for requests so if you do use ThreadLocals, you'll need to clean up after yourself once the request is finished (perhaps using a filter)
If you are the only developer in the project and you think you gain something: just do it! Because it is your time. But, be prepared to revert the decision and reorganize the code base later, as should be always the case.
Let's say there are ten developers on the project. Everybody might like to have its thread local variable to pass on parameters like currency, locale, roles, maybe it becomes even a HashMap....
I think in the end, not everything which is feasible, should be done. Complexity will strike back on you....
ThreadLocal can lead to memory leak if we do not set null manually once its out of scope.
I'm interested in the mediator object because it sounds useful, but deciphering code examples in order to learn how to interact with and build that object escapes me. I love code examples if they come with some explanations, however short. Would someone be able to just explain what I'm building when I build a mediator object?
Would a mediator object be a way to handle action events sent between classes? or does the mediator object simply serve better for consolidating like-code into one handy place?
I don't know if it's practical for convenience or if it's practical because there is no other way to do what it does. Any details, however "dumbed down", would be most excellent. Thanks in advance.
The mediator object is intended to do nothing itself. You should not move any logic that you already have into it, except maybe for some multiplexing/demultiplexing (when one object sends the same message to multiple other objects). The mediator is just an external interface (if it simultaneously serves as a facade), and definitely a message passing channel between pre-existing objects.
Likewise, a mediator should not be created until you are already perceiving the need for such a message passing channel. How does such a need look like? You already have a set of objects that start calling each other in increasingly complex ways. Those objects are storing references to each other; the number of such references is already getting bigger than the number of such objects themselves.
So instead of each object talking to each object (with a quadratic number of references and complicated graph of interactions) you introduce a star topology to interactions; everybody directly talks just to the mediator. It is then easier to instantiate, monitor, debug, extend, polymorphize...
Do not start introducing mediators too early or the overall complexity will grow instead of dropping.
I'm using an API providing access to a special server environment. This API has a wide range of Data objects you can retrieve from it. For Example APICar
Now I'd like to have "my own" data object (MyCar) containing all information of that data object but i'd like to either leave out some properties, augment it, or simply rename some of them.
This is because i need those data objects in a JSON driven client application. So when someone changes the API mentioned above and changes names of properties my client application will break immediatly.
My question is:
Is there a best practice or a design pattern to copy objects like this? Like when you have one Object and want to transfer it into another object of another class? I've seen something like that in eclipse called "AdapterFactory" and was wondering if it's wide used thing.
To make it more clear: I have ObjectA and i need ObjectB. ObjectA comes from the API and its class can change frequently. I need a method or an Object or a Class somewhere which is capable of turning an ObjectA into ObjectB.
I think you are looking for Design Pattern Adapter
It's really just wrapping an instance of class A in an instance of class B, to provide a different way of using it / different type.
"I think" because you mention copying issues, so it may not be as much a class/type thing as a persistence / transmission thing.
Depending on your situation you may also be interested in dynamic proxying, but that's a Java feature.
I have a Java system that consumes an API. A few days ago, we started facing the following problem: the remote API was receiving too many requests from my system. Back in the system's early days, it was not a major concern, but little by little the system's performance was getting worse and worse, since my data was growing and I made multiple requests for each entity. I noticed many of the network requests I made were not really necessary, since the data was not updated very frequently. So, I implemented a class that, when my system starts, makes an over-eager loading of all the remote API data. When I create/update an entity, I load it before any request is made. I treat deletion accordingly. And the remote API also notifies me when any change is made so I can stay updated even when this change is made outside my system.
What I really want to know is: is there any name for this practice? Any known design pattern
? I must say I've done a little research and I think it is a proxy pattern but, again, I'm not very sure (in fact, most of the design patterns look very similar), and I'm not really that much into design patterns.
I would call it a Cache System to what you implemented. Not sure if there is a dessign pattern for this though.
Also, the fact that the remote API notifies you when any change is made, might have been done using the observer pattern.
It's not quite a proxy pattern as the proxy pattern falls more under the heading of 'lazy loading'. From the description of the Proxy Pattern specified in
Design Patterns (Group of Four Book):
One reason for controlling access to an object is to defer the full
cost of its creation and initialization until we actually need to use
it
I'm not sure what you'd call it other than over-eager loading
I'm running a server which on occasion has to search what a client queries. I'd like to write the client query to disk for records, but I don't want to slow down the search anymore than I have to. (The search is already the bottleneck...)
So, when the client performs a search, I'm having the client's thread send a message to a singleton thread, which will handle the disk write, while the client thread continues to handle the client's requests. That way, the file on disk doesn't run into sync issues, and it doesn't slow the clients experience down.
I have a conceptual question here: is the singleton appropriate in this case? I've been using the singleton design pattern a little too much in my recent programming, and I want to make sure that I'm using it for its intended use.
Any feedback is greatly appreciated.
The singleton pattern is definitely overused and comes with its share of difficulties (unit-testing is the canonical example), but like everything in design, you need to weigh the pros and cons for your specific scenario. The singleton pattern does have its uses. There are options that may allow you to get the singleton behaviour, while alleviating some of the inherent issues:
Interception (often referred to as aspect oriented programming, though I've seen debate that they are not exactly the same thing... can't find the article I read on this at this time) is definitely an option. You could use any combination of construction injection, the decorator pattern, an abstract factory and an inversion of control container. I'm not up on my Java IoC containers, but there are some .Net containers that allow automatic interception (I believe Spring.Net does, so likely Spring (Java) has this built in). This is very handy for any type of cross-cutting concerns, where you need to perform certain types of actions across multiple layers (security, logging etc.). Also, most IoC containers allow you to control lifetime management, so you would be able to treat your logger as a singleton, without having to actually implement the singleton pattern manually.
To sum it up. If a singleton fits for your scenario (seems plausible from your description), go for it. Just make sure you have weighed the pros and cons. You may want to try a different approach and compare the two.