Created
June 29, 2020 08:16
-
-
Save bhawna94/57ca7817072bbae5bf398aec15ea7eb5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface DatabaseExecuter { | |
public void executeDatabase(String query); | |
} | |
class DatabaseExecuterImpl implements DatabaseExecuter { | |
@Override | |
public void executeDatabase(String query) { | |
System.out.println("Going to execute Query: " + query); | |
} | |
} | |
class DatabaseExecuterProxy implements DatabaseExecuter { | |
boolean ifAdmin; | |
DatabaseExecuterImpl dbExecuter; | |
public DatabaseExecuterProxy(String name, String passwd) { | |
if(name == "Admin" && passwd == "Admin@123") { | |
ifAdmin = true; | |
} | |
dbExecuter = new DatabaseExecuterImpl(); | |
} | |
@Override | |
public void executeDatabase(String query) throws Exception { | |
if(ifAdmin) { | |
dbExecuter.executeDatabase(query); | |
} else { | |
if(query.equals("DELETE")) { | |
throw new Exception("DELETE not allowed for non-admin user"); | |
} else { | |
dbExecuter.executeDatabase(query); | |
} | |
} | |
} | |
} | |
public class ProxyPatternExample { | |
public static void main(String[] args) throws Exception { | |
DatabaseExecuter nonAdminExecuter = new DatabaseExecuterProxy("NonAdmin", "Admin@123"); | |
nonAdminExecuter.executeDatabase("DELEE"); | |
DatabaseExecuter nonAdminExecuterDELETE = new DatabaseExecuterProxy("NonAdmin", "Admin@123"); | |
nonAdminExecuterDELETE.executeDatabase("DELETE"); | |
DatabaseExecuter adminExecuter = new DatabaseExecuterProxy("Admin", "Admin@123"); | |
adminExecuter.executeDatabase("DELETE"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment