Let's take an example, suppose you have a Data model [which has some attributes and getters, setters, optional methods]. In the context of a mobile application, in particular, an Android application, there can be two modes: Off-line or On-line. If the device is connected to a network, data is sent to the network stored in the deviceβs local database. In procedural form, someone can define two models as OnlineData, OfflineData and write the code as [The code is not exact, its like a pseudo-code]:
if(Connection.isConnected()){ OnlineData ond=new OnlineData(); ond.save();//save is called which stores data on server using HTTP. } else{ OfflineData ofd=new Onlinedata(); ofd.save();//save is called which stores data in local database }
A good approach to implementing this is to use the principles of OOPS:
The program for the interface is not running
Let's see how to do it. I am just writing code snippets that will more effectively represent what I mean. The following are snippets:
public interface Model { long save();//save method //other methods ..... } public class OnlineData extends Model { //attributes public long save(){ //on-line implementation of save method for Data model } //implementation of other methods. } public class OfflineData extends Model { //attributes public long save(){ //off-line implementation of save method for Data model } //implementation of other methods. } public class ObjectFactory{ public static Model getDataObject(){ if(Connection.isConnected()) return new OnlineData(); else return new OfflineData(); } }
and here is the code your client class should use:
public class ClientClass{ public void someMethod(){ Model model=ObjectFactory.getDataObject(); model.save();
It also follows:
Single Responsibility Principle [SRP]
because On-line and Off-line are two different responsibilities that we can integrate into Single save () using the if-else statement.
source share