Java design pattern - java

I am new to design pattern. I have a small project in which java classes use dummy data when not connected to server. I have if condition in class that switches between dummy data and server data depending on a flag . Is there a better way this can be implemented?

Instead of controlling your code with an 'if' statement, you should write an interface that defines all the methods you will need to interact with the server, and reference that interface instead of a concrete implementation. Then, have your 'dummy data' implement that interface.
The advantage of this is that your code will be written in a way that is not dependent upon the server implementation. This will allow you to change details on the server without changing your client's implementation.

I would recommend using the Repository pattern to encapsulate your data layer. Create an interface for the Repository and have two concrete implementations, one for dummy data and the other for server data. Use the Factory pattern to create your Repository. The Factory would return the correct concrete implementation of the Repository based on whether you are connected or not.

You need a Data Access Object, or an object which acts as a proxy between the requesting program and the data.
You ask the DAO for the data, and based on it's configuration, it responds with your server data, or other data. That other data might be newly instantiated classes, data from text files, etc.
In this image, the "Business Object" is your program, the "Data Access Object" is the reconfigurable gate-keeper, the "Transfer Object" is the object representation of the data requested, and the "Data Source" is the interface which you previously used to get to the data. Once the "Data Access Object" is in place, it is not hard to add code to it to "select" the desired data source (DummyDataSource, FileDataSource, JDBCDataSource, etc).

Proxy_pattern suits best for your use case.
In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes.
You can find explanation for tutorials point example here:
Proxy Design Pattern- tutorialspoint.com example
Have a look at below articles
oodesign proxy
tutorials point proxy
sourcemaking proxy example
dzone proxy example

If you want a design pattern, then State pattern is what you need.

Related

Shareable Interface in Javacard: use cases and implementation

[Context]
I need to send data from one applet to another. In addition, one of the applets needs to be deleted and reinstalled. After the installation, data exchange between the applets needs to be possible.
Is Shareable Interface useful to realize that?
[Theoretical]
In general, I would like to know the cases where shareable interface is a good idea and What its principal use.
[Practice]
I took example from this answer but it does not work. I think I did not understand how to implement. I tried to create two applets in the same package, one master and one slave. But I got 6F 00 when slave is selected. I did other test with two packages. But I got same error.
Shareable allows you to exchange the data between applets on the card.
There are some limitations though, the main being the fact that one cannot freely exchange internal objects. Only objects allowed for sharing can pass via the Shared interface. The example you mention uses some proprietary “SharedArray” interface to implement this.
By default, only standard global objects such as APDU backing array, or various STK objects can be used for this purpose.
In addition, it is possible to pass simple value types such as byte and short via the Shared interface methods.
In some cases, especially in STK environments the Shared interface is used to initiate the operations while the data is passed via a separate EF on the card which is used as a “mailslot”.
Regarding, the implementation itself, one needs to remember that Shareable interface is just a marker and as such you need to define a concrete interface that inherits from Shareable to be able to use it in the application.
The above interface constitutes a hard dependency for any application using or implementing this interface.
As a result, the package containing the interface definition cannot be deleted if any of the other applets/libraries use it.
One of the common options is to define the interface in a separate library and install it first. Since it is not likely to change, and if it does you would change the AID,version anyway, all other clients can be freely installed and deleted.
Lastly, please keep in mind Sharable interface should be used with care due to security issues associate with data sharing.
I highly recommend getting a copy of “Java Card Technology for Smart Cards: Architecture and Programmer's Guide” which covers these topics and much more.
Answering your question in order
[Context]
Shareable interface is used when one applet(Client Applet) need to access methods from another applet(Server applet) provided both the applets are located in different packages.Applets in different packages are separated by a firewall to prevent access to applet data across package.
Applet instances can be deleted in any order but Applet package should deleted in order. That is, first client package is deleted than server package is deleted.
[Theoretical]
Shareable interface is useful for object sharing since firewall restrict object sharing between packages.
For proper uses cases kindly go through this white paper - www.usenix.org/legacy/event/smartcard99/full_papers/montgomery/montgomery.pdf
[Practice]
Kindly check solution for shareable interface implementation - https://stackoverflow.com/a/57200926/4752262

Design pattern for mapping field from one object to another

I am writing a component that fits into a 3rd party framework. The component exports orders into a specific file format, ready to be transported to a separate backend system.
The backend system has a very different view of the data, with specific restrictions on field lengths and formats that the framework doesnt have. Therefore i need to be able to:
1. Store/know about these rules
2. Take the data from the framework
3. Transform based on the data received and the rules i mentioned in point 1
4. Write the transformed data to file
Are there any design patterns for this type of functionality. Particularly, where to put the mapping rules:
- xml config
- directly in a class
- something else?
Adapter is used to adapt from one interface to another.
Different ways to accomplish, but you can simply implent two interfaces on the one adapter class. And/Or make the adapter composed of an instance of another class or classes.
The Adapter pattern (more specifically Object Adapter pattern) contains an instance of the class it wraps. In this situation, the adapter makes calls to the instance of the wrapped object. The pattern itself allows the interface of an existing class to be used from another interface. Hope this helps!

Best Practice (Design Pattern) for copying and augmenting Objects

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.

Proxy & Memento Patterns

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.

How to prepopulate model objects with test data from file?

I have some model objects I'm using in my Java client application. Later these model objects will be populated / retrieved from remote services (e.g. SOAP). Now I want to do manual / automatic testing of the frontend before implementing these services. The model objects are mostly POJO and I want to store some sample test data in files and populate them with some easy method.
E.g. having model object School (with name (String) and teachers (List)) and Teacher with lastname and firstname, I want to store actual test data in some XML / text file and create some schools containing teachers from these data.
What are you using in this situation? I'm not familiar with TTD yet, but I can't imagine that there is no generic framework for doing this.
[edit]
I've choosen Spring to mock up my sample data / services, but the other alternatives mentioned here would have worked as well.
Sounds like a good use of XML serialization. You can use any XML serialization tool you like: XStream, etc.
Another nice tool is SOAP UI. If you point it to the WSDL for your service it'll create the XML request for you. Fill in the values and off you go. These can be saved, so perhaps that's a good way to generate test cases.
You can also use Spring to mock your remote service(s) and their responses.
In this case, all you have to do is loading an applicationContext that will simulate your backend system(s) by replying exactly what you want for your test purpose.
Why not keep the test data in Java? You have no extra stages, formats or libraries to deal with. It's fast and you have the power and familiarity of Java on your side.
First, I'd agree with duffymo that XStream and SOAP UI are viable options. However, I've also used the approach described by Tom Hawtin, as described below.
A helper class constructs a set of test instances of the model classes, some valid and some invalid in specific ways, and builds the appropriate object graphs. An initial test case uses a valid object object graph. Successive tests substitute invalid objects for valid ones in the initial setup, checking that the appropriate errors are returned.
The helper class provides a single point of control for constructing objects whose contents are appropriately related for the scenarios needed in testing.

Categories