Add another method to every implementation of my Interface in all implementations - java

I have an interface:
public interface InterfaceListener {
void eventEnd();
}
Some methods receives this InterfaceListener as a parameter and every one of course implement it on his own way. For example:
myObject.callMethod(false,InterfaceListener() {
#Override
public void eventEnd() {
//do some extra code
}
});
Now I want to add some changes, to insure that every implementation in eventEnd() will be called only after it's passed another method - callMyExtraMethod() that common to all the calls, something like that:
myObject.callMethod(false,InterfaceListener() {
#Override
public void eventEnd() {
if (callMyExtraMethod()) {
//do some extra code
}
}
});
Any ideas how can I add it to the logic without passing on every implementation and adding manually that same check to all?

Rename eventEnd to eventEndImpl in IDE. Then add default method:
public interface InterfaceListener {
default void eventEnd() {
if (callMyExtraMethod()) {
eventEndImpl();
}
}
void eventEndImpl();
// Uncomment, if this method must belong to the same class.
// bool callMyExtraMethod();
}

If you are using Java 7, one way to achieve this -
Create an AbstractListener class with abstract methods
eventEnd and callMyExtraMethod and a template method templateMethod
public abstract class AbstractListener {
public abstract void eventEnd();
public abstract boolean callMyExtraMethod();
public void templateMethod(){
if(callMyExtraMethod()){
eventEnd();
}
}
}
Now you can create the Anonymous classes and call the templateMethod(). This will ensure the callMyExtraMethod() check before invoking eventEnd()
AbstractListener listener = new AbstractListener() {
#Override
public void eventEnd() {
// your implementation
}
#Override
public boolean callMyExtraMethod() {
//System.out.println("I am callMyExtraMethod");
return true;
}
};
listener.templateMethod();
Hope this helps.

Related

Unity-Encrypting String using the Decorator Pattern

I'm trying to apply the decorator pattern to making an object that encrypts a word into a certain encryption, like the L337 method, which replaces letters like 9 with g, or 4 with r. Basically, I want to type a word into an inputfield and show the encrypted word in a text object. But I can't get the L337 decorator to inherit from the main decorator class. It won't accept the keyword 'super', so I tried the base word, but then when I implement Encrypt, it won't take the object newEncryption. Could someone help me figure out how to put this pattern together please?
I basically know what the decorator pattern is. It's making an object, making a basic decorator, and making a specific decorator, and instantiating the object with the decorating for exclusive methods and features.
public class Encryption : MonoBehaviour
{
public static InputField inputBox;
public static Text outputText;
public interface IEncryption { void Encrypt(); }
public class TextEncryption : IEncryption
{
public void Encrypt()
{
string currentText = inputBox.text;
outputText.text = currentText;
}
}
public abstract class encryptionDecorator : IEncryption
{
protected IEncryption tempEncryption;
public encryptionDecorator(IEncryption newEncryption)
{
tempEncryption = newEncryption;
}
public void Encrypt()
{
tempEncryption.Encrypt();
}
}
public class L337EncryptionDecorator : encryptionDecorator
{
public L337EncryptionDecorator(IEncryption newEncryption) : base(newEncryption)
{
print("Encrypting L337 Code");
}
public void Encrypt()
{
}
}
}
I think you actually want to use tempEncryption, but you didnt really tell where you could not use newEncryption so im guessing.
But anyway, I hope this will clear some things up. Its slightly edited from your code so I didnt need to put GUI stuff, but you could just CnP it to unity.
using UnityEngine;
public class Encryption : MonoBehaviour {
public interface IEncryption {
void Encrypt();
}
public class TextEncryption : IEncryption {
public void Encrypt() {
}
}
public abstract class EncryptionDecorator : IEncryption {
protected IEncryption tempEncryption;
public EncryptionDecorator(IEncryption newEncryption) {
//this will be called when you override the constructor
Debug.Log("In EncryptionDecorator constructor: " + newEncryption.GetType());
tempEncryption = newEncryption;
}
//if you are going to override a method in a child class,
//declare it either abstract ("no body; passes implementation to child") or
//virtual ("allows for a base implementation")
public virtual void Encrypt() {
Debug.Log("In EncryptionDecorator.Encrypt(): " + tempEncryption.GetType());
tempEncryption.Encrypt();
}
}
public class L337EncryptionDecorator : EncryptionDecorator {
public L337EncryptionDecorator(IEncryption newEncryption) : base(newEncryption) {
//newEncryption is a parameter, think of it as sort of a local variable.
//but since you pass it down to the parent class, it gets assigned to tempEncryption
//the base-class constructor is called first!
Debug.Log("In L337EncryptionDecorator constructor: " + newEncryption.GetType());
}
//this overrides the base implementation. you can call it with
//base.Encrypt() though.
public override void Encrypt() {
//you have no parameters here, but you could use the inherited variable tempEncryption because you declared it protected
Debug.Log("In L337EncrytionDecorator.Encrypt(): " + tempEncryption.GetType());
//base refers to the base class
base.Encrypt();
}
}
void Start() {
IEncryption encryption = new L337EncryptionDecorator(new TextEncryption());
encryption.Encrypt();
}
}
or maybe i missed what this is all about?!

Print statement not called in anonymous class passed to class constructor

I have two classes and one interface.
Interface:
public interface MyBirthdayEvent {
void itsMyBirthday();
}
First class:
public class MyBirthdayButton
{
public void addOnClickedListener(MyBirthdayEvent mbe){}
}
Second class:
public class MyBirthday {
private MyBirthdayButton myBirthdayButton = new MyBirthdayButton();
MyBirthday() {
myBirthdayButton.addOnClickedListener(new MyBirthdayEvent() {
public void itsMyBirthday() {
System.out.println("Happy Birthday");
}
});
}
}
Then in main, I have this:
public class TestThisStuff {
public static void main(String[] args) {
MyBirthday myBirthday = new MyBirthday();
}
}
As can be seen from the code, I am using an anonymous class in the MyBirthday constructor. In doing so, I am trying to get the string "Happy Birthday" to print to the console.
My problem is, when I call the MyBirthday constructor in main by making a new myBirthday object, I am not seeing the string "Happy Birthday" print to the console. Shouldn't it print to the console? If not, what I am doing wrong?
What you can do is this:
public interface MyBirthdayEvent {
void itsMyBirthday();
default void invoke() {
itsMyBirthday();
}
}
...
public class MyBirthdayButton
{
public void addOnClickedListener(MyBirthdayEvent mbe){
mbe.invoke();
}
}
...
Also, it will work without it, but use a lambda rather than an anonymous inner class. This looks much better.
MyBirthday() {
myBirthdayButton.addOnClickedListener(() ->
System.out.println("Happy Birthday"));
}
you can move System.out.println("some words")statement to your MyBirthdayEventconstructor
it didn't show in your console because you haven't invoke the method

Java: Is it possible to always execute a certain function before other functions are called? (Like #Before in JUnit)

Is there a way to always execute a function before any other function of a class is called?
I have a class where I need to refresh some fields always before any function is called:
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
Because it seems to be bad programming, I don't want to call refresh at the beginning of every other function. Since other persons are going to work on this project as well, there would be the danger, that somebody extends the calls and doesn't call refresh.
JUnit has a solution for this with the #Before-Annotation. Is there a way to do this in other classes as well?
And by the way: If you know a programming pattern wich solves this problem in another way than executing a function everytime any function is called, that would be very helpful, too!
Use a dynamic proxy in which you can filter to those methods before which your specific "before" method should be called. And call it in those cases before dispatching the call. Please see the answer from How do I intercept a method invocation with standard java features (no AspectJ etc)?
UPDATE:
An interface is needed to be separated for the proxy. The refresh() method cannot remain private. It must be public and part of the interface (which is not nice here) to be able to be called from the proxy.
package CallBefore;
public interface ExampleInterface {
void function1();
void function2();
void otherFunction();
void refresh();
}
Your class implements that interface:
package CallBefore;
public class Example implements ExampleInterface {
#Override
public void function1() {
System.out.println("function1() has been called");
}
#Override
public void function2() {
System.out.println("function2() has been called");
}
#Override
public void otherFunction() {
System.out.println("otherFunction() has been called");
}
#Override
public void refresh() {
System.out.println("refresh() has been called");
}
}
The proxy which does the trick. It filters the needed methods and calls refresh().
package CallBefore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ExampleProxy implements InvocationHandler {
private ExampleInterface obj;
public static ExampleInterface newInstance(ExampleInterface obj) {
return (ExampleInterface) java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new ExampleProxy(obj));
}
private ExampleProxy(ExampleInterface obj) {
this.obj = obj;
}
#Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
try {
if (m.getName().startsWith("function")) {
obj.refresh();
}
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return result;
}
}
The usage:
package CallBefore;
public class Main {
public static void main(String[] args) {
ExampleInterface proxy = ExampleProxy.newInstance(new Example());
proxy.function1();
proxy.function2();
proxy.otherFunction();
proxy.refresh();
}
}
Output:
refresh() has been called
function1() has been called
refresh() has been called
function2() has been called
otherFunction() has been called
refresh() has been called
This may not solve your exact problem but at least could be a starting point if you are allowed considering a re-design. Below is a simple implementation but with some small touches I believe you can achieve a more elegant solution. BTW, this is called Dynamic Proxy Pattern.
First thing you need is an interface for your class.
public interface Interface {
void hello(String name);
void bye(String name);
}
public class Implementation implements Interface {
#Override
public void hello(String name) {
System.out.println("Hello " + name);
}
#Override
public void bye(String name) {
System.out.println("Bye " + name);
}
}
Then java.lang.reflect.Proxy class comes to help. This class is able to create an instance for a given interface at runtime. It also accepts an InvocationHandler which helps you to capture method calls and looks like this.
public class InvocationHandlerImpl implements InvocationHandler {
private final Object instance;
public InvocationHandlerImpl(Object instance) {
this.instance = instance;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
System.out.println("Before");
result = method.invoke(instance, args);
System.out.println("After");
} catch (Exception e){
e.printStackTrace();
throw e;
} finally {
System.out.println("finally");
}
return result;
}
}
After all your client code will look like this.
Interface instance = new Implementation();
Interface proxy = (Interface)Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[] { Interface.class },
new InvocationHandlerImpl(instance));
proxy.hello("Mehmet");
proxy.bye("Mehmet");
Output for this code is
Before
Hello Mehmet
After
finally
Before
Bye Mehmet
After
finally
I would define getters for every field and do the refreshment inside the getter. If you want to avoid unrefreshed access to your private fields at all, put them in a superclass (together with the getters which call refresh).
Depending on your project structure, it may be also sensible to introduce a separate class for all data that is regularly refreshed. It can offer getters and avoid that anyone accesses the non-refreshed fields.
Not in Java SE, but if you are using Java EE, you could use interceptors.
For standalone applications, you could consider using a bytecode manipulation framework, like javassist.
You can have a protected getter method for data. Access getData method instead of using data field. Child classes will see only getData and will have updated data every time.
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
protected int getData(){
refresh();
return data;
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
It is better to write another method which will be made protected(accessible to the child classes) which will call first the refresh method and then call the function.
This way the data would be refreshed before the function is called everytime(As per your requirement).
eg:
protected void callFunction1(){
refresh();
function();
}
Thanks,
Rajesh
You should use Decorator in this case. Decorator is a good choice for something like interceptor. Example here: https://msdn.microsoft.com/en-us/library/dn178467(v=pandp.30).aspx

making a class with abstraction is also encapsulation?

Encapsulation is said to be wrapping up of data and method and hidding functionality(method and instance variable) that is not needed for outside of this object
my question is only making a variable private and public is encapsulation ? or making a class with abstraction is also encapsulation ?
For Example:
I have Switch(Electic Switch) class doing on or off
to make a Switch class i have used abstraction
and i encapsulated Switch class with using abstraction so that i can map
motor or bulb or any electric Instrument
public class Switch {
private boolean isOff = true;
private ISwitchListener listener;
public Switch(ISwitchListener listener) {
this.listener = listener;
}
public void trigger() {
isOff = !isOff;
if(isOff) {
listener.off();
} else {
listener.on();
}
}
}
public class Bulb implements ISwitchListener {
#Override
public void on() {
// TODO Auto-generated method stub
System.out.println("bulb is glittering");
}
#Override
public void off() {
// TODO Auto-generated method stub
System.out.println("bulb is not glittering");
}
}
public interface ISwitchListener {
public void on();
public void off();
}
public class Executor {
public static void main(String[] args) {
// TODO Auto-generated method stub
Switch swt = new Switch(new Bulb());
swt.trigger();
}
}
if i am not using abstraction here , i would have class like below
public class Switch {
private boolean isOff = true;
public void trigger() {
isOff = !isOff;
Bulb b =new Bulb();
if(isOff) {
b.off();
} else {
b.on();
}
}
}
When i want to map Motor to Switch i need to change class as bleow
public class Switch {
private boolean isOff = true;
public void trigger() {
isOff = !isOff;
Bulb b =new Bulb();
if(isOff) {
b.off();
} else {
b.on();
}
}
}
public class Motor {
public void on() {
// TODO Auto-generated method stub
System.out.println("Motor is rotating");
}
public void off() {
// TODO Auto-generated method stub
System.out.println("Motor is getting off to rotate");
}
}
In general, no, abstraction and encapsulation are two different things. Specifically, abstraction means removing detail that is unnecessary for the intended purpose of the code or model. For example, if you write a program to calculate how much paint you need for a house, your model of a house needs to include the surface area, but doesn't need to include the address, or the size of the yard.
Encapsulation means hiding the internal workings of an object or module, such that the coupling between objects can be controlled and readily changed. If there were no encapsulation, clients of the object might directly reference its internal elements, which would mean that you would have to change all the clients if you modified the object.
Regarding the code example, I think a better solution would be to create an interface "Switchable" and have Motor and Bulb implement it. Like so:
public interface Switchable {
void on();
void off();
}
public class Motor implements Switchable {
public void on() {
System.out.println("Motor is rotating");
}
public void off() {
System.out.println("Motor is getting off to rotate");
}
}
public class Switch {
private boolean isOff = true;
private Switchable switchable;
public Switch(Switchable switchable) {
this.switchable = switchable;
}
public void trigger() {
isOff = !isOff;
if(isOff) {
switchable.off();
} else {
switchable.on();
}
}
}
Hope that helps.
Your first example is an example for dependency injection => you let the caller decide which concrete class the class "Switch" needs to do its job.
In fact it is the "opposite" of data hiding as the outside world has to know some implementation details of the class "Switch". => it needs an implementation of ISwitchListener
As #T I said, it can be a method hiding for example from Java 8 you can create default implementation in the interface, so you can hide that in the class where implement the interface.
But encapsulation is about field (instance variable) hiding. Creating a private member (instance variable) and creating setter and getter. You will reach the value only via dedicated methods.
If you want to encapsulate your methods, you need to deal with accessibility (see default and protected modifiers).
So the answer for your question is: No. Making a class with abstraction is not encapsulation.
Abstraction and Encapsulation are interrelated. You can say Abstraction is needed to Encapsulate the system.
Abstraction is when a client system does not need to know more than what is in the interface.
Encapsulation is when a client of a module is not able to know more than what is in the interface.
Pleas refer this page for a beautiful article on this topic.

How to overload a method with generic parameter in java? [duplicate]

I have FinanceRequests and CommisionTransactions in my domain.
If I have a list of FinanceRequests each FinanceRequest could contain multiple CommisionTransactions that need to be clawed back. Dont worry how exactly that is done.
The class below (very bottom) makes me feel all fuzzy and warm since its succint and reuses existing code nicely. One problem Type erasure.
public void clawBack(Collection<FinanceRequest> financeRequestList)
public void clawBack(Collection<CommissionTrns> commissionTrnsList)
They both have the same signature after erasure, ie:
Collection<FinanceRequest> --> Collection<Object>
Collection<CommissionTrns> --> Collection<Object>
So eclipse complainst that:
Method clawBack(Collection) has the same erasure clawBack(Collection) as another method in type CommissionFacade
Any suggestions to restructure this so that it still an elegant solution that makes good code reuse?
public class CommissionFacade
{
/********FINANCE REQUESTS****************/
public void clawBack(FinanceRequest financeRequest)
{
Collection<CommissionTrns> commTrnsList = financeRequest.getCommissionTrnsList();
this.clawBack(commTrnsList);
}
public void clawBack(Collection<FinanceRequest> financeRequestList)
{
for(FinanceRequest finReq : financeRequestList)
{
this.clawBack(finReq);
}
}
/********COMMISSION TRANSACTIOS****************/
public void clawBack(CommissionTrns commissionTrns)
{
//Do clawback for single CommissionTrns
}
public void clawBack(Collection<CommissionTrns> commissionTrnsList)
{
for(CommissionTrns commTrn : commissionTrnsList)
{
this.clawBack(commTrn);
}
}
}
Either rename the methods, or use polymorphism: use an interface, and then either put the clawback code in the objects themselves, or use double-dispatch (depending on your design paradigm and taste).
With code in objects that would be:
public interface Clawbackable{
void clawBack()
}
public class CommissionFacade
{
public <T extends Clawbackable> void clawBack(Collection<T> objects)
{
for(T object: objects)
{
object.clawBack();
}
}
}
public class CommissionTrns implements Clawbackable {
public void clawback(){
// do clawback for commissions
}
}
public class FinanceRequest implements Clawbackable {
public void clawBack(){
// do clwaback for FinanceRequest
}
}
I prefer this approach, since I'm of the belief your domain should contain your logic; but I'm not fully aware of your exact wishes, so I'll leave it up to you.
With a double dispatch, you would pass the "ClawbackHandler" to the clawback method, and on the handler call the appropriate method depending on the type.
I think your best option is to simply name the method differently.
public void clawBackFinReqs(Collection<FinanceRequest> financeRequestList) {
}
public void clawBackComTrans(Collection<CommissionTrns> commissionTrnsList) {
}
In fact, it's not too bad, since you don't get anything extra out of having the same name on them.
Keep in mind, that the JVM will not decide which method to call at runtime. As opposed to virtual methods / method overriding resolution of overloaded methods are done at compile time. The Java Tutorials on method overloading even points out that "Overloaded methods should be used sparingly...".
Here is a trick with overloading by the second varargs parameter for the CommissionFacade class from the question:
public class CommissionFacade {
public void clawBack(Collection<FinanceRequest> financeRequestList, FinanceRequestType ...ignore) {
// code
}
public void clawBack(Collection<CommissionTrns> commissionTrnsList, CommissionTrnsType ...ignore) {
// code
}
/*******TYPES TO TRICK TYPE ERASURE*******/
private static class FinanceRequestType {}
private static class CommissionTrnsType {}
}
The code snippet to fast-check this trick works:
import java.util.ArrayList;
class HelloType {
public static void main(String[] args) {
method(new ArrayList<Integer>());
method(new ArrayList<Double>());
}
static void method(ArrayList<Integer> ints, IntegerType ...ignore) {
System.out.println("Hello, Integer!");
}
static void method(ArrayList<Double> dbs, DoubleType ...ignore) {
System.out.println("Hello, Double!");
}
static class IntegerType {}
static class DoubleType {}
}

Categories

Resources