I am having the following problem. I have implemented a pipeline processing and sometimes I have to release resources like for example Files. At the same time my pipeline is asynchronous so it immediately releases control I am having a shutdown method in the Non-lamda implementation. I am not able to plug it in using lambdas. My current code looks like this:
#FunctionalInterface
public interface Stage<T,Q> {
public Q process(T toProcess);
}
#FunctionalInterface
public interface IntermediatStage<T,Q> extends Stage<T,Q> {
public default <P> IntermediatStage<T,P> nextStage(Stage<Q,P> nextStage) {
return (T t) -> {return nextStage.process(this.process(t)); };
}
}
I need to subsequently call a shutdown method on the different stages. The problem is that chaining them by a default method I don't have visibility on them. Is it possible somehow when I add the Stages to also be able to add a shutdown hook which I can call independently later based on the fact that the pipeline is asynchroneus ?
Thanks
You can’t solve everything with interfaces and lambda expressions only. This looks like a simple task for an ordinary class having a pattern like this:
public final class Stage<T,R> {
static final Runnable NO_OP = () -> {};
public static <I,O> Stage<I,O> create(Function<I,O> f) {
return new Stage<>(f, NO_OP);
}
public static <I,O> Stage<I,O> create(Function<I,O> f, Runnable cleanup) {
return new Stage<>(f, cleanup);
}
private final Function<T,R> actualAction;
private final Runnable cleanup;
private Stage(Function<T,R> f, Runnable r) {
actualAction=f;
cleanup=r;
}
public <P> Stage<T,P> nextStage(Function<R,P> nextStage) {
return new Stage<>(actualAction.andThen(nextStage), cleanup);
}
public <P> Stage<T,P> nextStage(Function<R,P> nextStage, Runnable nextCleanup) {
return new Stage<>(actualAction.andThen(nextStage),
cleanup==NO_OP? nextCleanup: () -> { cleanup.run(); nextCleanup.run(); });
}
public R process(T t) {
return actualAction.apply(t);
}
public Function<T, R> getActualAction() {
return actualAction;
}
public void cleanup() {
cleanup.run();
}
public Runnable getCleanup() {
return cleanup;
}
}
The Stage class is simple and invariant, but it’s actual behavior is determined by the Function and Runnable instances which can be created via lambda expression, if you wish. You can create and chain either, using a plain function only or by providing a function and a cleanup action. You’ll get two different chains for the functions and cleanup actions, thus can execute them independently.
Without more information about how resources are cleaned up, one could imagine something like
#FunctionalInterface
public interface Stage<T,Q> {
Q process(T toProcess);
static <T,Q> Stage<T,Q> of(Stage<T,Q> stage){
return stage;
}
default Stage<T,Q> withRelease(Consumer<T> releaser){
return t -> {
Q q = process(t);
releaser.accept(t);
return q;
};
}
}
which you could invoke like
Stage.of(Thing::process).withRelease(Thing::close)
Related
I have class three classes. Pref, ClassA, and ClassB.
public class Pref{
public static ArrayList<Pref> prefList;
public static Observable<ArrayList<Pref>> observable;
public static void loadData(){
prefList = getFromDb();
observable = Observable.just(prefList);
}
}
Application runs the ClassA First.
public ClassA{
public ClassA(){
initObserver();
setObserver();
}
public void initObserver(){
Pref.loadData();
}
public void setObserver(){
Observer<ArrayList<Pref>> obs = new Observer() {
#Override
public void onSubscribe(Disposable dspsbl) {
System.out.println("Subscribed");
}
#Override
public void onNext(ArrayList<Pref>> t) {
System.out.println("Loading Preference.");
//Need to do some other works here.
}
#Override
public void onError(Throwable thrwbl) {
}
#Override
public void onComplete() {
}
};
Pref.observable.subscribe(obs);
}
}
Now I want to change the list from ClassB.
public class ClassB{
private void changeList(){
Pref.prefList = loadDataFromSomeSource();
}
}
When I run ClassA, the System.out works fine. But when I change the list from ClassB nothing happens. My question is, is the right way to work with Rxjava. Is it for Rxjava built? If I am wrong how can I achieve this functionality? How can I write several ClassA like classes so that When the ClassB::changeList() runs, I can listen it in ClassA?
By setting Pref.prefList = loadDataFromSomeSource();, you assign a new list instance to Pref.prefList. This will not update Pref.observable in any way, because this still refers to the old Pref.prefList instance.
I also think that you can not use an Observable to publish events through it. As far as I understand your situation, you need an ObservableSource (see http://reactivex.io/RxJava/javadoc/io/reactivex/ObservableSource.html). For example, it is implemented by PublishSubject. You could use it like this:
PublishSubject<String> source = PublishSubject.create();
source.subscribe(System.out::println);
source.onNext("test 1");
source.onNext("test 2");
source.onNext("test 3");
Or, in your case: in class Pref, you can use public static PublishSubject<ArrayList<Pref>> source = PublishSubject.create();. When loading the data, you can publish the new data using onNext, like this in ClassB: Pref.source.onNext(loadDataFromSomeSource())
For the sample code below...
Is there a way to chain instances of different classes? The example provided is a failed attempt for wiring up methods belonging to different class instances.
Also, In the same example, Client2 is sharing the error object with Client3. What is a more efficient way of sharing objects between subclasses and unassociated classes?
For clarity, i have also commented inline.
Thank You for your time and help.
Sample Code
public class StubRunner
{
public run(){
ClientFactory client = new ClientFactory();
//not correct. But, this is how i want to finally chain methods
//belonging to different class instances. Please advise.
client.getClient1().testClient1().getClient2().testClient2().assert(...);
}
}
public class ClientFactory
{
public Client1 getClient1(){return new Client1();}
public Client2 getClient2(){return new Client2();}
}
public class BaseClient
{
public Errors errors = null;
}
public class Client1 extends BaseClient
{
public void testClient1(){...}
}
public class Client2 extends BaseClient
{
public void testClient2()
{
//here i am directly passing the error object
//what is a better way?
//is there a more efficient way to make the SAME error object
//available to Client3
new Client3(this.errors).testClient3();
...
}
}
public class Client3 extends BaseClient
{
public Client3(Errors errors){this.errors = errors;}
public void testClient3(){...}
}
I would normally use lambda expressions for the cases when I want to program a short chain of method calls but I want the methods to change relatively to any kind of state. As for your scenario, each of your test would be a lambda expression and it would mean that I would pass the testClient4 method to the testClient3 method, the testClient3 method to the testClient2 method, etc. However, the code becomes more and more ugly as your chain of method calls becomes long.
=> You can use Fluent interface: you would have each method doing some logic and then returning an instance on which you can call the next inline methods you want to execute.
ClientFactory.getClient1() : Client1
Client1.testClient1() : Client1 (i.e. return this)
Client1.getClient2() : Client2
Client2.testClient2() Client2 (i.e. return this)
...
Obviously, each instance would need to have a reference to the next inline instance, knowing the one it will call (Client1 would have a reference to Client2, Client2 to Client3, etc).
This would work but I'm not a fan in this scenario! I'd say it's more a trick than clean coding. You should use fluent interface with each client separately unless one of your method is actually returning another instance:
client1.testClient1().testClient2().testClient3()
with each test method returning an instance of the next client if there is a good reason for it
but it wouldn't make sense to interpose the getClient methods between the test methods...
I am not really getting what your need really is, however in the actual state of the code it cannot even compile since you are trying to execute methods from a "Client" object from a void method return.
If you do not know how many clients and from which type you are going to get, I would simply use a list.
If you want to chain the clients using the 'testClient' method, then first this method should return the next client (which is a really awkward way to chain objects by the way), then you should start using more abstraction and overriding technics.
Basically, there's no need to know what object you are dealing with as long as it is a "BaseClient", but if you name the child methods "testClient1", "testClient2" etc ... you basically breaking it and you need to start thinking of what you are actually getting and adapt your code accordingly.
Finally, there's no need for a factory here, but if you want one, it should be static.
Here is a working example of this, again I do not really comprehend what you wanna do so it may not solve your issue, but it's a working solution to "chaining instances":
Main:
public class Foo
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
StubRunner stub = new StubRunner();
stub.run();
}
}
Stubrunner:
public class StubRunner implements Runnable
{
public void run(){
Object clients = ClientFactory.getClient1();
while (null!= clients && clients instanceof BaseClient) {
clients = ((BaseClient) clients).test();
}
}
}
Base:
public abstract class BaseClient
{
public Exception errors = null;
public BaseClient() {};
public BaseClient(Exception errors) {
this.errors = errors;
}
public abstract BaseClient test();
public void checkErrors() {
System.out.println(this.toString());
assert null == errors;
}
}
Client 1:
public class Client1 extends BaseClient
{
public BaseClient test(){
checkErrors();
return new Client2();
}
}
Client 2:
public class Client2 extends BaseClient
{
public BaseClient test()
{
checkErrors();
return new Client3(this.errors);
}
}
Client 3:
public class Client3 extends BaseClient
{
public Client3(Exception errors) {
super(errors);
}
public BaseClient test() {
checkErrors();
return null;
}
}
Factory:
public final class ClientFactory
{
private ClientFactory() {};
public static Client1 getClient1(){return new Client1();}
public static Client2 getClient2(){return new Client2();}
}
This outputs the following:
test.Client1#15db9742
test.Client2#6d06d69c
test.Client3#7852e922
Is there a way to chain instances of different classes? The example provided is a failed attempt for wiring up methods belonging to different class instances.
client.getClient1().testClient1().getClient2().testClient2().assert(...);
In order to chain methods like this, each method must return a reference to an object which supports the method which you want to call. However, each test method returns void.
In this case, method chaining seems very questionable because you are operating on different types. Often methods in a chain like this will just return this; so that another method can be called on the exact same object which started the chain.
Additionally, the names of your methods suggest that you are attempting to implement some automated testing of your code. You should learn about established testing techniques and libraries. In particular, JUnit is commonly used in Java and variations in other languages. There are certain techniques that are considered good practice when writing tests in frameworks such as this.
To be clear here, you should certainly not mix testing code with production code.
Also, In the same example, Client2 is sharing the error object with Client3. What is a more efficient way of sharing objects between subclasses and unassociated classes?
//here i am directly passing the error object
//what is a better way?
//is there a more efficient way to make the SAME error object
//available to Client3
new Client3(this.errors).testClient3();
The only way to send an object to a class is to pass a parameter, either to the constructor or to a method. This is how Java works.
Note that there is very little overhead because you are passing a reference variable. You are not copying the entire object. This means that both the current instance of Client2 and the new instance of Client3 have references to the same error object.
Now testClient1() could return the client factory and such. But that is very convoluted.
Another regulatory syntax is to override a context providing class.
new ClientFactory() {{
getClient1().testClient1();
getClient2().testClient2().assert(...);
}};
Here an initializing block ("anonymous constructor") will provide a context.
Then a bit of chaining can be done when testClient2 returns a Client2.
It can be a clean and useful design, for instance for my ambiguous grammar parser AnyParser on sourceforge.net (purely a craftmanship piece of work).
Thank you everyone for the great help. Your advise has allowed me to arrive at the following working solution. Maybe it is not the best, so seeking your valuable time and your expertise to direct to a better solution.
Given some remarks my naming convention being fishy, i have tried to amend them to a certain extent. Kindly bear with me.
Objective was:
To chain instances of different classes
To share objects between subclasses and unassociated classes
Problem description:
There are 4 tasks to be performed: Task1 to Task4.
Each task is unique. But sometimes, to complete a task we need to perform mixed Task: refer Task3 >> performMixedTasks()
To complete a piece of work we need to complete a set of Tasks.
State.java
public class State {
public Boolean ISAUDITED = false;
public int ERRORCODE = 0;
public String ERRORTEXT = "";
public void raise(int code, String msg){
this.ERRORCODE = code;
this.ERRORTEXT = msg;
}
}
BaseClient.java
public abstract class BaseClient {
public State state;
public BaseClient(){
this.state = new State();
}
public BaseClient(State state){
this.state = state;
}
public ClientFactory getTest(){
return new ClientFactory(state);
}
public Boolean Assert(){
if(state.ERRORCODE == 0){
System.out.println("Parsing was successful.");
return true;
}
else{
System.out.println("Parsing was not successful.");
return false;
}
}
public abstract BaseClient GoTo();
}
Task1.java
public class Task1 extends BaseClient {
public Task1(){ GoTo(); }
public Task1(State state){ super(state); GoTo(); }
public Task1 performTask1(){
if(!state.ISAUDITED)
{
System.out.println("perform Task1");
state.ISAUDITED = true;
}
return this;
}
#Override
public BaseClient GoTo() {
if(state.ISAUDITED){
new Task2(state).performTask2();
}
return this;
}
}
Task2.java
public class Task2 extends BaseClient{
public Task2(){ GoTo(); }
public Task2(State state){ super(state); GoTo(); }
public Task2 performTask2(){
if(state.ISAUDITED)
{
System.out.println("perform Task2");
state.ISAUDITED = false;
}
return this;
}
#Override
public BaseClient GoTo() {
if(!state.ISAUDITED){
new Task1().performTask1();
}
return this;
}
}
Task3.java
public class Task3 extends BaseClient {
public Task3(){ }
public Task3(State state){ super(state); }
public Task3 GoTo(){
if(!state.ISAUDITED) {new Task1(state).performTask1();}
System.out.println("Opening Task3");
return this;
}
public Task3 performTask3(){
try
{
this.GoTo();
System.out.println("Submitted Task3 Data");
}
catch(Exception e){
state.raise(1, e.getMessage());
}
return this;
}
public Task3 performMixedTasks(){
new Task4(state).performTask4();
this.performTask3();
return this;
}
}
Task4.java
public class Task4 extends BaseClient {
public Task4(){ }
public Task4(State state){ super(state); }
public Task4 GoTo(){
if(!state.ISAUDITED) {new Task1(state).performTask1();}
System.out.println("Opening Task 4");
return this;
}
public Task4 performTask4(){
try
{
this.GoTo();
System.out.println("Submitted Task 4 Data");
}
catch(Exception e){
state.raise(1, e.getMessage());
}
return this;
}
}
ClientFactory.java
public class ClientFactory {
State state;
public ClientFactory(){
state = new State();
}
public ClientFactory(State state){
this.state = state;
}
public Task3 loadTask3(){return new Task3(state);}
public Task4 loadTask4(){return new Task4(state);}
}
StubRunner1.java
public class StubRunner1 {
public static void main(String[] arg)
{
ClientFactory test = new ClientFactory();
test.loadTask3()
.performTask3()
.getTest()
.loadTask4()
.performTask4()
.Assert();
}
}
**RESULT IS**
perform Task1
Opening Task3
Submitted Task3 Data
Opening Task4
Submitted Task4 Data
Parsing was successful.
StubRunner2.java
public class StubRunner2 {
public static void main(String[] args) {
ClientFactory test = new ClientFactory();
test.loadTask3()
.performMixedTasks()
.Assert();
}
}
**RESULT IS**
perform Task1
Opening Task4
Submitted Task4 Data
Opening Task3
Submitted Task3 Data
Parsing was successful.
Let's say I have a class called Server, and I would like to allow others to write Plugins for it. Say Plugin is an Interface that extends Runnable and adds a single method: void init(...). It is the job of a plugin to collect data and send it to the server. When the time comes to send data to the server, however, how does it do this? Coming from C and C++ I am looking for a thinking along the lines of a function pointer. It seems to be possible in Java though I have not found examples outside the Java Standard Class Library.
How do I pass a method reference to the init method such that it can be stored by the Plugin, and then how do I invoke the method whenever the Plugin wants to send data? For now say that the desired Server method is: void sendData(Integer data).
For example:
// Inside Server
Plugin p = new PluginImplementation();
p.init(this::sendData);
// Plugin init
public void init(?? sendMethod) {
storedSendMethod = sendMethod;
// ...
}
// Plugin run
public void run() {
// ...
storedSendMethod(x) // Sends data to server
// ...
}
Using java.util.function.Function we can pass a function as an argument to a method, and then use apply() to apply it to the relevant arguments. Here's an example:
import java.util.function.Function;
public class FunctionDemo {
// we will pass a reference to this method
public static Integer square(Integer x) {
return x * x;
}
// this method accepts the function as an argument and applies it to the input: 5
public static Integer doSomething(Function<Integer, Integer> func) {
return func.apply(5);
}
public static void main(String[] args) {
// and here's how to use it
System.out.println(doSomething(FunctionDemo::square)); // prints 25
}
}
Additional version with multiple parameters (passed as an array):
public static Integer sum(Integer[] x) {
Integer result = 0;
for(int i = 0; i < x.length; i++)
result += x[i];
return result;
}
public static void main(String[] args) {
Integer[] arr = {1,2,3,4,5};
System.out.println(doSomething(Play::sum, arr));
}
public static Integer doSomething(Function<Integer[], Integer> func,
Integer[] arr) {
return func.apply(arr);
}
If the method is void sendData(Integer data) that corresponds to a consumer that takes an Integer and returns a void which is covered by the built in Consumer<Integer> interface which has an accept(Integer) method that will invoke your function when called.
So your code will look like this:
public void init(Consumer<Integer> sendMethod) {
storedSendMethod = sendMethod;
// ...
}
// Plugin run
void run() {
// ...
storedSendMethod.accept(x) // Sends data to server
// ...
}
As a sidenote, having an init method is probably a bad Java design. you are better moving the initialization to the constructor if possbile
Plugin p = new PluginImplementation( this::sendData);
In java, you do it with a callback,
This is your callback interface,
public interface SendCallback {
public void doSend(Object toSend);
}
This is the plugin interface, All plugin must implement this interface
public interface Plugin extends Runnable {
public void init(SendCallback callback);
}
This is the Server's code.
public class Server {
Plugin plugin;
SendCallback callback = new SendCallback() {
public void doSend(Object toSend) {
// logic to send object 'toSend'
}
}
public Server() {
plugin = new MyPlugin();
plugin.init(callback);
}
}
This is your plugin implementation.
public class MyPlugin implements Plugin {
SendCallback callback = null;
Object x = null;
public void init(SendCallback callback) {
this.callback = callback;
}
public void run() {
x = "Somthing"; // initialize the x object
callback.doSend(x);
}
}
You will notice, the server define the callback implementation.
The plugin will invoke the callback's method doSend.
I hope, this helps
There is method reference in Java 8, however you can just pass a whole object and call its sendData() method. In a 'plug-in' situation, using interfaces for each helps the plugin and the server have 'looser' coupling.
public interface Server {
void setData(...);
}
public class MyPlugin implements plugin {
private Server server;
void init(Server s ) {
this.server = s;
}
void run() {
...
this.server.setData(...);
...
}
}
interface Server{
...
void sendData(String message);
}
Plugin doesn't need a function reference, you can use the Server interface for informing Plugin to know about that method.
class PluginX implements Plugin{
...
private Server server;
void init(Server server) {
this.server = server;
}
public void run() {
// ...
server.sendData(x) // Sends data to server
// ...
}
}
I am trying to use RabbitMQ and based on different message, different implements should be called.
I set the message format as of JSON, and there is a field "callType", the value of it is the class name implements a common interface. e.g, all implementations have implements interface "Task", and I have implementation of "TaskImp1","TaskImp2","TaskImp3".
So the code should be like
if (callType=="TaskImp1")
((Task)TaskImp1).runTask()
if (callType=="TaskImp2")
((Task)TaskImp2).runTask()
if (callType=="TaskImp3")
((Task)TaskImp3).runTask()
But could it be more flexible? If later I develop a new one "TaskImp4", I don't want to change the calling code, is it possible to have java automatically pick the right implementation since the callType is actually the class name of the implementation.
Yes, for example, through Java reflection (What is reflection and why is it useful?). Reflection has a performance cost though (Java Reflection Performance)
Sure: put your Task instances in a map:
private Map<String, Task> tasksByName = new HashMap<>();
...
tasksByName.put("TaskImp1", new TaskImp1());
tasksByName.put("TaskImp2", new TaskImp2());
tasksByName.put("TaskImp3", new TaskImp3());
...
String callType = message.getCallType();
Task task = tasksByName.get(callType);
task.runTask();
Also, read How do I compare strings in Java?
You have an opportunity to use Strategy here. So for e.g. you could do like:
public class MyTask {
private Task task;
public MyTask(Task task) {
this.task = task;
}
public void doSomething() {
task.runTask();
}
public static void main(String args[]) {
MyTask task = new MyTask(new TaskImpl1());//or even you could use setTask() api to inject task at runtime rather than doing cast on compile time.
task.doSomething();
task = new MyTask(new TaskImpl2());
task.doSomething();
task = new MyTask(new TaskImpl3());
task.doSomething();
}
}
In this way you could make your code extensible. Tomorrow if you have taskImpl4, you could code it independently and inject in MyTask without even touching MyTask class implementation.
As #ovdsrn already said you can use reflection. Simple example would be something like (the key is getTask static method. Also, note that, when you are using Class.forName you must specify whole "path" (package) for your class)
// ITask.java
package main;
public interface ITask {
void doSomething();
}
// Task1.java
package main;
public class Task1 implements ITask {
#Override
public void doSomething() {
System.out.println("Task1");
}
}
// Task2.java
package main;
public class Task2 implements ITask {
#Override
public void doSomething() {
System.out.println("Task2");
}
}
// main
package main;
public class JavaTest {
private static ITask getTask(String name) {
try {
Class<?> cls = Class.forName(name);
Object clsInstance = (Object) cls.newInstance();
return (ITask)clsInstance;
} catch (Exception e) { // you can handle here only specific exceptions
return null;
}
}
public static void main(String[] args) {
String name = args.length > 0 ? args[0] : "Task2";
ITask task = getTask("main." + name);
if (task != null) {
task.doSomething();
}
else {
System.out.println("can not make instance of class: " + name);
}
}
}
I've recently started using C#, and I wanted to find an equivalent method to this. I do not know what this is called, so I will simply show you by code.
With Java, I was able to create an interface like so:
public interface Event {
public void execute();
}
And pass this interface in a method's parameter like so:
public class TestEvent {
ArrayList<Event> eventList = new ArrayList<Event>();
public void addEvent(Event event){
eventList.add(event);
}
public void simulateEvent(){
addEvent(new Event() {
public void execute(){
//functionality
}
} );
}
public void processEvents(){
for(Event event : eventList)
eventList.execute();
}
}
EDIT : My question is revolved on the simulatEvent method from the TestEvent class, and if such an action is possible with C#.
I wanted to know if there was a way to do something similar to this with C#, (instantiating the interface in the simulateEvent method) and what this is actually called. Thank you!
Woof...ok, permit me to generalize a bit:
So in Java, you need a way to pass functions around. Java does not inherently support functions as first-class citizens, and this was one reason behind the implementation of anonymous classes - packaged groups of functions that can be declared inline and passed (as interfaces) to methods/other classes that will then call these functions.
In C#, functions are first-class citizens, and can be declared as either Delegates, Func<>s, or Action<>s. Let's try a comparison (of sorts):
Some sort of Java-y construct (my Java's fairly old, so bear with me):
public interface IDoSomething {
public int Return42();
public bool AmIPrettyOrNot(string name);
public void Foo();
}
public void Main(String[] args) {
DoStuff(new IDoSomething() {
public int Return42() { return 42; }
public bool AmIPrettyOrNot(string name) { return name == "jerkimball"; }
public bool Foo(int x) { ... }
});
}
public void DoStuff(IDoSomething something) { ... }
The (very rough) equivalent of this in C# would be:
public void Main(string[] args)
{
Func<int> returns42 = () => 42;
Func<string,bool> amIPretty = name => name == "jerkimball";
Action<int> foo = x => {};
}
Now, as others have mentioned, you usually see this pattern on the Java side when dealing with the handling of events - likewise on the C# side:
public class Foo
{
// define the shape of our event handler
public delegate void HandlerForBarEvent(object sender, EventArgs args);
// declare our event
public event HandlerForBarEvent BarEvent;
public void CallBar()
{
// omitted: check for null or set a default handler
BarEvent(this, new EventArgs());
}
}
public void Main(string[] args)
{
var foo = new Foo();
// declare the handler inline using lambda syntax
foo.BarEvent += (sender, args) =>
{
// do something with sender/args
}
foo.CallBar();
}
Note that we can also give it something with the same "shape":
public void MyHandler(object sender, EventArgs args)
{
// do stuff
}
public void Main(string[] args)
{
var foo = new Foo();
// that method above is the same "shape" as HandlerForBarEvent
foo.BarEvent += MyHandler;
foo.CallBar();
}
But it's also used in Java to define what Threads do, if memory serves (i.e., Runnable) - and we can do this as well in C#:
var thread = new Thread((Action)(() =>
{
// I'm the threads "run" method!
});
thread.Start();
Now, other stuff - enumeration:
public void processEvents(){
for(Event event : eventList)
eventList.execute();
}
C# has the same idea, just called differently:
public void processEvents()
{
// edit: derp, 'event' is a keyword, so I'm
// renaming this, since I won't get into why
// you could also use #event...
foreach(var evt in eventList)
{
evt.Execute();
}
}
EDIT: It looks like your question is about anonymous interface implementations instead of events. You can use the built-in Action delegate type instead of your Event interface.
You can then Action instances using lambda expressions. Your code would look like:
public class TestEvent
{
List<Action> eventList = new List<Action>();
public void addEvent(Action event){
eventList.add(event);
}
public void simulateEvent(){
addEvent(() => {
});
}
public void processEvents(){
for(Action event : eventList)
event();
}
}
You can use the delegate syntax instead of using () => { .. .} i.e.
delegate() { ... } in simulateEvent.
C# doesn't support anonymous interface implementations, so if your interface has multiple methods then you'll have to define a concrete class somewhere. Depending on the usage you could just have this class contain delegate properties which you can supply on creation e.g.
public class Delegates
{
public Action Event { get; set; }
public Func<string> GetValue { get; set; }
}
You can then create it like:
var anon = new Delegates
{
Event = () => { ... },
GetValue = () => "Value"
}