Java Design Pattern

I'm new to design. I have a small project where java classes use dummy data when not connected to a server. I have a condition in a class that switches between dummy data and server data depending on a flag. Is there a better way to accomplish this?


source to share

5 answers

Instead of manipulating your code with an "if" statement, you should write an interface that defines all the methods needed to communicate with the server, and reference that interface instead of a specific implementation. Then, your "dummy data" implements this interface.

The advantage of this is that your code will be written in a way that is independent of the server implementation. This will allow you to modify data on the server without changing the client implementation.



You need a data access object, or an object that acts as a proxy between the requesting program and the data.

You ask the DAO for data and based on its configuration, it responds with your server data or other data. Other data could be new instances of classes, data from text files, etc.

In this image , "Business Object" is your program, "Data Access Object" is a reconfigurable gatekeeper, Transfer Object "is an object representation of the requested data, and" Data Source "is the interface you previously used for data access When the Data Access Object is in place, it's easy to add code to it to “select” the correct data source (DummyDataSource, FileDataSource, JDBCDataSource, etc.).



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



Proxy_pattern is the best fit for your use.

In short, a proxy is a wrapper or agent object invoked by the client to access the real service object behind the scenes.

enter image description here

You can find an explanation for the example here with tutorial examples:

Sample Proxy Template

Look below articles

oodesign proxy

proxy training point

example of creating a proxy server

dzone proxy example



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



All Articles