Anonymous interface implementation in php - java

In Java we can do like this..
interface Inter {
public void run()
}
class Test {
public Test(Inter inter){
inter.run();
}
}
new Test(new Inter() {
#Override
public void run() {
//Some Task;
}
}
But in php I got error while doing like this. Isn't it possible to do this in php?

A little late, but you can do this in php:
new Test(new class implements Inter {
public function run()
{
// Some Task;
}
});

Related

How to iterate over mixed interface implementation array?

I have the following classes.
interface interface1() {
void function1()
}
interface interface2 extends interface1() {
void function2()
}
class implementation1 implements interface1 () {
#Override
void function1() {
// Implement
}
}
class implementation2 implements interface2 () {
#Override
void function1() {
// Implement
}
#Override
void function2() {
// Implement
}
}
class Main() {
List<interface1> interfaceList = new ArrayList();
for (interface : interfaceList) {
if (interface instanceOf(interface2)) {
interface.function2();
}
}
}
Could you please tell if there is a way to prevent using instanceOf? I read visitor pattern could be used but I am not getting the exact changes to be done.
Following are the classes after discussing with Alex R below (instanceOf is avoided since it is not recommended, visitor pattern is avoided since it still leads to empty visit functions). Please let me know if this can be done better using other design patterns.
interface interface1() {
void function1();
boolean isFunction2Applicable();
default void function2() {
}
}
class implementation1 implements interface1 () {
#Override
void function1() {
// Implement
}
#Override
boolean isFunction2Applicable() {
return false;
}
}
class implementation2 implements interface1 () {
#Override
void function1() {
// Implement
}
#Override
boolean isFunction2Applicable() {
return true;
}
#Override
void function2() {
// Implement
}
}
class Main() {
List<interface1> interfaceList = new ArrayList();
for (interface : interfaceList) {
if (interface.isFunction2Applicable()) {
interface.function2();
}
}
}
One way to do so is to define some method in the base interface and override it in the sub-interfaces or implementations. In the following example I'm using a default method but you don't have to do so; the method can be abstract and only be implemented in the implementations:
interface I1 {
void function1();
default void execute() {
function1();
}
}
interface I2 extends I1 {
void function2();
#Override
default void execute() {
function1();
function2();
}
}
public static void main(String[] args) {
List<I1> ifaces = new ArrayList<>();
for (I1 iface : ifaces) {
iface.execute();
}
}

Trying to write a class that allows to do something before the Thread starts and after the Thread finishes

I am trying to write a Utility class that helps to execute a task on a Separate Thread, providing the ability to do something before the task starts, and something after the task ends.
Something similar to android's AsyncTask
Here is such a class.
class MySync
{
public void preExecute() {}
public void executeInBackground() {}
public void postExecute() {}
public final void execute()
{
threadExecute.start();
}
private final Thread threadExecute = new Thread()
{
#Override
public void run()
{
try
{
MySync.this.preExecute();
MySync.this.executeInBackground();
MySync.this.postExecute();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};
}
Here is how this class is supposed to be used. Consumer of the class will override the methods as per the requirement.
class RegisterStudent extends MySync
{
#Override
public void preExecute()
{
System.out.println("Validating Student details. Please wait...");
try
{
Thread.sleep(2000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
#Override
public void executeInBackground()
{
System.out.println("Storing student details into Database on Server. Please wait...");
try
{
Thread.sleep(4000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
#Override
public void postExecute()
{
System.out.println("Student details saved Successfully.");
}
}
And finally starting the task:
public class AsyncDemo
{
public static void main(String... args)
{
new RegisterStudent().execute();
}
}
It seems to work fine. My question is, is this the correct way of achieving the Objective as mentioned in the Title? Any suggestions on how best this can be implemented?
What I don't like with your approach is the fact that you create a new thread each time you create a new instance of MySync which is not scalable if you intend to create a lot of instances of your Object moreover it is costly to create a Thread, if I were you I would use an executor in order to limit the total amount of threads allocated to execute your tasks asynchronously, here is how you can do it if you want to use only one thread:
ExecutorService executor = Executors.newFixedThreadPool(1);
I would also re-write your code for something like this:
public abstract class MySync implements Runnable {
#Override
public final void run() {
try {
preExecute();
executeInBackground();
} finally {
postExecute();
}
}
protected abstract void preExecute();
protected abstract void executeInBackground();
protected abstract void postExecute();
}
This way you define the whole logic for all the implementations.
Then you can submit your task like this:
executor.submit(new RegisterStudent());
What's bad about this is that you're forcing users to extend your class. In java you can only extend 1 class. So a framework should not take that away.
Rather use an interface:
public interface AsyncTask {
public default void preExecute() {}
public default void executeInBackground() {}
public default void postExecute() {}
}
And have users pass that to your utility class:
class MySync
{
private AsyncTask task;
public MySync(AsyncTask task) {
this.task = task;
}
public final void execute()
{
threadExecute.start();
}
private final Thread threadExecute = new Thread()
{
#Override
public void run()
{
try
{
MySync.this.task.preExecute();
MySync.this.task.executeInBackground();
MySync.this.task.postExecute();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};
}
Loader is exactly what you are looking for.
Here is introduction for loader
https://developer.android.com/guide/components/loaders.html
https://developer.android.com/reference/android/content/Loader.html

How to reimplement Java listeners with anonymous classes in C#

I am trying to replicate my Java code in C# and I wish to know how can I replicate this Java functionality in C#.
Util.java
public class Util
{
public void function(String s, final SetAvailabilityStatusListener setStatusListener)
{
// ....
}
public static interface SetAvailabilityStatusListener {
public void setAvailabilityStatus(Status status);
}
}
Activity.java
public class Activity
{
public void anotherFunction()
{
util.function("name", new SetAvailabilityStatus()
{
#Override
public void setAvailabilityStatus(Status status) {
loginSetAvailabilityStatus(status);
}
}
}
}
Use delegates. They are used in C# instead of Java anonymous classes that implement interfaces.
public class Util
{
public void Function(String s, Action<Status> setStatusListener)
{
// ....
setStatusListener("myStatus");
}
}
public class Activity
{
private Util util = new Util();
public void AnotherFunction()
{
util.Function("name", status => LoginSetAvailabilityStatus(status));
}
public void LoginSetAvailabilityStatus(string status){
//do something with status
}
}
I was unable to find suitable duplicate, so:
1. C# does not have anonymous classes like Java does, but no one stops you from creating needed listener classes manually
public class Util
{
public void Function(String s, ISetAvailabilityStatusListener setStatusListener)
{
// ....
}
public interface ISetAvailabilityStatusListener {
public void SetAvailabilityStatus(Status status);
}
}
public class Activity
{
private class MySetAvailabilityStatusListener: Util.ISetAvailabilityStatusListener
{
public void SetAvailabilityStatus(Status status)
{
// do your handling, but nested classes have some differences with anonymous Java classes, so it may require additional infrastructure.
}
}
public void AnotherFunction()
{
utilObj.Function("name",
new MySetAvailabilityStatusListener())
}
}
It is so-called observer design pattern (just without unregistration method!!).
2. As it has been already suggested by #AndreySarafanov you can use Action Delegates and lambda expressions:
public class Util
{
public void Function(String s, Action<Status> statusChangeListener)
{
// ....
}
}
public class Activity
{
public void AnotherFunction()
{
utilObj.Function("name",
(status) =>
{
loginSetAvailabilityStatus(status);
}
}
}
3. C# has another more simple mechanism to deal with event-handling(subsrciption) mechanics - events and delegates
public class StatusEventArgs : EventArgs
{
//...
}
public class Util
{
public void SomeFunction()
{
// ....
if (this.OnAvailabilityChanged != null)
OnAvailabilityChanged(this, new StatusEventArgs(status));
}
public event EventHandler<StatusEventArgs> OnAvailabilityChanged
}
public class Activity
{
public void AvailabilityStatusChangedHandler(object sender, EventArgs<Status> eventArgs)
{
}
public void AnotherFunction()
{
utilObj.OnAvailabilityChanged += this.AvailabilityStatusChangedHandler;
}
}
It does not allow you to associate the name property with event handler, well, you can overcome it with special registration method, but it will reduce the usability of events, so you should probably stick with another solution.

Subscription model with generics - implement multiple generic interfaces

So I tried to make a subscription model with generics.. it looked nice, but now I'm running into some issues.
Receiver
public interface Receiver<E> {
public void receive(E event);
}
Subscription registry
public class ClientRegistry<T> {
private Set<Receiver<T>> clients = new HashSet<Receiver<T>>();
public void subscribe(Receiver<T> client) {
clients.add(client);
}
public void unsubscribe(Receiver<T> client) {
clients.remove(client);
}
public void broadcast(T eventObject) {
for(Receiver<T> client: clients) {
client.receive(eventObject);
}
}
}
Sounds good so far, eh?
Now the problems come:
public class Screen implements Receiver<KeyEvent>, Receiver<MouseMoveEvent> {
#Override
public void receive(KeyEvent event)
{
// work
}
#Override
public void receive(MouseMoveEvent event)
{
// work
}
}
Now this is invalid syntax:
The interface Receiver cannot be implemented more than once
with different arguments: Receiver<MouseMoveEvent> and Receiver<KeyEvent>
How can I alter my system to keep it as generic as possible, but make it work?
Don't make the Screen class itself implement the two Receiver interfaces. Instead, use composition:
public class Screen {
private Receiver<KeyEvent> keyReceiver = new Receiver<KeyEvent>() {
...
};
private Receiver<MouseEvent> mouseReceiver = new Receiver<MouseEvent>() {
...
};
}
I would reverse the order, and use a Visitor Pattern:
import java.util.*;
interface Event{
void receive(Receiver receiver);
}
class KeyEvent implements Event{
#Override
public void receive(Receiver receiver){
receiver.receive(this);
}
}
class MouseEvent implements Event {
#Override
public void receive(Receiver receiver){
receiver.receive(this);
}
}
interface Receiver {
void receive(KeyEvent event);
void receive(MouseEvent event);
}
class ClientRegistry {
private Set<Receiver> clients = new HashSet<Receiver>();
public void subscribe(Receiver client) {
clients.add(client);
}
public void unsubscribe(Receiver client) {
clients.remove(client);
}
public void broadcast(Event eventObject) {
for(Receiver client: clients) {
eventObject.receive(client);
}
}
}
public class Screen implements Receiver {
public void receive(KeyEvent event) {
//work
System.out.println("Processing key event");
}
public void receive(MouseEvent event) {
//work
System.out.println("Processing mouse event");
}
public static void main(String[] args){
ClientRegistry registry = new ClientRegistry();
registry.subscribe(new Screen());
registry.broadcast(new MouseEvent());
}
}
There is not way to generify the Receiver interface, but it is indeed type safe and as you can see, I reverse the order, since now it is the event the one which chooses the receiver and not otherwise.

Implement the Event-Dispatch-Thread in the right way

I need a Event-Dispatch-Thread in my programm.
I want go from this:
public Controller {
this.login= new Login(this);
}
to this:
public Controller {
Runnable guiCreator = new Runnable() {
public void run() {
this.login= new Login(this);
}
};
SwingUtilities.invokeLater(guiCreator);
}
I know where the mistake in the second version is. But the Login(Controller controller) constructor needs the controller reference...
How i do this?
Try using Controller.this to refer to the outer/top level instance of the class
public Controller() {
Runnable guiCreator = new Runnable() {
public void run() {
login= new Login(Controller.this);
}
};
SwingUtilities.invokeLater(guiCreator);
}

Categories

Resources