Paneri
Paneri

Reputation: 125

Java design pattern

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?

Upvotes: 3

Views: 521

Answers (5)

Ravindra babu
Ravindra babu

Reputation: 38950

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.

enter image description here

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

Upvotes: 0

Edwin Buck
Edwin Buck

Reputation: 70959

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).

Upvotes: 1

Kevin Junghans
Kevin Junghans

Reputation: 17540

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.

Upvotes: 1

mtmurdock
mtmurdock

Reputation: 13062

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.

Upvotes: 5

Roman
Roman

Reputation: 66216

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

Upvotes: -1

Related Questions