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.
Related
I need to make a couple of services that will talk to both Amazon S3 and Riak CS.
They will handle the same operations, e.g. retrieve images.
Due to them returning different objects, in S3's case an S3Object. Is the proper way to design this to have a different class for each without a common interface?
I've been thinking on how to apply a common interface to both, but the return type of the methods is what's causing me some issues, due to them being different. I might just be going wrong about this and probably should just separate them but I am hoping to get some clarification here.
Thanks all!
Typically, you do this by wrapping the responses from the various external services with your own classes that have a common interface. You also wrap the services themselves, so when you call your service wrappers they all return your wrapped data classes. You've then isolated all references to the external service into one package. This also makes it easy to add or remove services.
A precise answer to your question would require knowing the language you are using and/or the platform. Eric in his answer above is correct that wrapping the data inside one of you own class is one way to handle this. However, depending on the language, the details of the final implementation will vary and the amount of work required when adding possible return value type will also vary.
In Java for example one way to handle this would be to return an heterogeneous container. Take a look at this thread:
Type safe heterogeneous container pattern to store lists of items
I really need your help regarding a design pattern which I can use, because right now I can't think of the best solution.
I need something which can accomplish the following thing.
Currently I have 3 objects :
NotificationOne.java
NotificationTwo.java
NotificationThree.java
Each one, represents basically the same thing, but they have nothing in common when it comes to fields/attributes.
These are actually some JSON's which I will map into objects, when they arrive via a JMS Queue.
Now, what I really need to do, is to transform these 3 objects to a common object, by interpreting their fields in a particular way for each one. Easy to done 'till now.
The real question is, what would be the best design pattern to apply, considering that in time, there will be more and more types of Notifications which will have to be transformed from something to a common object.
The flow of things will be something like this :
-JSON gets in the queue
-I will map the JSON to a POJO
-Pass the POJO to a possible factory, which will have to deal with each type of Notification class, so it can transform it into something which we'll call it CommonNotification.
-CommonNotification has to be stored into DB
-A particular field of CommonNotification has to be used as a notification payload.
Based on this flow, what's the best pattern which I can use.
Thanks in advance.
You're saying the conversion depends on the type of notification? Like zapl said, in that case, I would create a common interface and let the three notification classes do the conversion. The design is very simple. Everybody who creates a new notification, knows that it should implement the interface and hence, knows that a conversion should be done.
Strictly theoretically speaking you're right in that a POJO should be a POJO, but I wouldn't make my design any more complicated than needed in this case. An interface and polymorphism is the way to go here.
Next to that, creating a common notification doesn't have any side effects in the system. So it's not that your POJO is modifying any system state. It just has some logic which is very POJO specific. It belongs in the POJO.
Use the Decorator pattern.
The ConcreteDecorator just adds responsibilities to the original
Component.
You can have different concrete decorator for different output but the responsibilities from your original component will be there in every output if that's what you want.
See http://www.oodesign.com/decorator-pattern.html
I guess this is a fairly generic object oriented question, but I am coming to the conclusion that I don't think enough in terms of objects.
I have two classes, a Person class and a People class. I will be reading and writing these (from and to the sharedPerferencesFile) from several activities. Right now I have a PersistData class that handles reading and writing. When I want to read or write these guys I get an instance of the PersistData class and then call methods like, persistData.write(person); or persistData.write(people);
Is this a good way to do this, or should I move the read and write code into the Person and People class?
I usually use a class i call settingsprovider, calling something like new SettingsProvider(this).getPerson(); and new SettingsProvider(this).setPerson(person); so yes, this is exactly how i would do it.
What you are doing looks to be correct. SharedPreference is a common file which is shared by all the components in the process. I mean all the classes in an application. So, your way of keeping PersistData and accessing it from person and people class looks clean and right approach.
As sharedPreference is a singlefile so the data will reamin persistant.
It depends on how you see / define the responsibilites of your classes. A Person does not necessarily need to know how to store it in shared preferences so something like Person#saveToPrefs() could be seen as bad design (tight coupling to shared preferences)
PersistData on the other hand does not need to know how the serialized format of a person looks in detail so that approach has it's weakness here.
I guess the cleanest way is to split the whole thing. A class that knows how to store stuff into shared preferences and a class that knows how to create serialized data of itself but does not care how that serialized data is used.
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.
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.