Definition -
This provides the ability to have effective communication between two modules or objects within the same module. This provides centralized control over the system.
Scenario -
Let us take an example of an object wanting to write into a filesystem. In this case we will have a mediator to which all the objects will communicate and write into the file.
Based on the above scenario -
1) filemediatorinterface class who provides the implmentation guidelines
2) A filemod class which wants to modify a file.
3) A File class which is the one to be modified.
4) A filemediator which controls which object gets to perform action.
Place to use -
1) When you have too many objects from a system speaking too many objects of other system.
2) You have very structured communication channel
The code for the above is present in the link here
This provides the ability to have effective communication between two modules or objects within the same module. This provides centralized control over the system.
Scenario -
Let us take an example of an object wanting to write into a filesystem. In this case we will have a mediator to which all the objects will communicate and write into the file.
Based on the above scenario -
1) filemediatorinterface class who provides the implmentation guidelines
package MediatorPattern;
public interface ifilemediator {
public void addrequest(filemod f);
public void addfile(File f);
public void givecontrol(File f, filemod fm);
}
2) A filemod class which wants to modify a file.
package MediatorPattern;
public class filemod {
String modname;
File filename;
public filemod(String name, File file) {
this.modname=name;
this.filename=file;
}
public void modifyfile(File f) {
System.out.println("Modifying file : "+f.filename);
}
}
3) A File class which is the one to be modified.
package MediatorPattern;
public class File {
public String filename;
public File(String name) {
this.filename=name;
}
}
4) A filemediator which controls which object gets to perform action.
package MediatorPattern;
import java.util.ArrayList;
public class filemediatorImpl implements ifilemediator{
ArrayList<filemod> fm=new ArrayList<filemod>();
ArrayList<File> f=new ArrayList<File>();
@Override
public void addrequest(filemod f) {
System.out.println("Adding request :"+f.modname+ " into the queue");
fm.add(f);
}
@Override
public void givecontrol(File f, filemod fm) {
System.out.println("Giving control to filemod "+fm.modname+" over the file "+f.filename);
fm.modifyfile(f);
}
@Override
public void addfile(File f) {
System.out.println("Fetching file "+f.filename+ " for modification");
}
}
Place to use -
1) When you have too many objects from a system speaking too many objects of other system.
2) You have very structured communication channel
The code for the above is present in the link here
No comments:
Post a Comment