Starting method in all implemented classes - java

I'm kind of new to Java and have a rather simple question:
I have an interface, with a method:
public interface Interface_Updatable {
public void updateViewModel();
}
I implement this interface in several classes. Each class then of course has that method updateViewModel.
Edit: I instantiate these classes in a main function. Here I need code that calls updateViewModel for all objects that implement the interface.
Is there an easy way to do it combined? I don't want to call every method from every object instance separately and keep that updated. Keeping it updated might lead to errors in the long run.

The short form is: no, there's no simple way to "call this method on all instances of classes that implement this interface".
At least not in a way that's sane and maintainable.
So what should you do instead?
In reality you almost never want to just "call it on all instances", but you have some kind of relation between the thing that should trigger the update and the instances for which it should be triggered.
For example, the naming of the method suggests that instances of Interface_Updatable are related to the view model. So if they "care" about changes to the view model, they could register themselves as interested parties by doing something like theViewModel.registerForUpdates(this), the view model could hold on to a list of all objects that registered like this and then loop over all the instances and calls updateViewModel on each one (of course one would need to make sure that unregistration also happens, where appropriate).
This is the classical listener pattern at work.
But the high-level answer is: you almost never want to call something on "all instances", instead the instances you want to call it on have some relation to each other and you would need to make that relation explicit (via some registration mechanism like the one described above).

There is no easy way to call this method on all classes that implement this interface. The problem is that you need to somehow keep track of all the classes that implement this interface.
A possible object-oriented way to do this would be passing a list containing objects that are instances of classes that implement the Interface_Updateable interface to a function, and then calling updateViewModel on each object in that list:
public void updateViewModels(List<Interface_Updateable> instances) {
for(var instance : instances) {
instance.updateViewModel();
}
}

Related

Java Interface Design - Helper Methods

I have an interface like so
public interface Manager {
public void manage();
}
Now, all Managers will need to load work to manage, however, I have mixed feelings about adding public void loadWork() to the interface...
On one hand, all Managers will do this, but on the other hand, users of a Manager class will not need to know about loadWork().
Question: Is it bad practice to add "helper" or "setup" type methods to an interface?
It's not always a bad idea to add "setup" methods in an interface. For example, Java EE has an interface called ServletContextListener that is purely meant to make setup and shut down.
It's even sometimes acceptable to make interfaces with methods you should actually never directly call such as the Runnable or the Callable interface.
Being said that, it seems is that you want to force your developers to implement a loadWork() method in Manager but you also want to hide it from the class' users.
As you say, one option is adding the method in the interface but this way the method will be accessible (which you don't want). If you don't want the method to have visibility I see two options:
Make the class Manager an abstract class and add a loadWork() protected method.
Create an interface called LoadWorker with a method loadWork(). Then create an abstract class AbstractManager that implements Manager and has as a private/protected LoadWorker field. This way, even though loadWork() is public, it's not accessible from AbstractManager's users as it is called through a protected/private field (LoadWorker).
At the end it comes to a balance between overengineering and good design. It's up to you to take the decision following the specific needs. Nevertheless, there is no 'perfect solution'.

Benefit of factory class over other polymorphism

I'm trying to figure out the purpose of factory classes in Java. Everywhere I look it says the purpose is
to create objects without exposing the creation logic to the client
to refer to newly created object using a common interface
Examples show an interface, e.g.
public interface Shape {
void draw();
}
with some concrete classes implementing this interface e.g.
public class Circle implements Shape {
#Override
public void draw() {
// Draw circle
}
}
and a factory, e.g.
public class ShapeFactory {
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}
// implement other types of shape
return null;
}
}
Use of the factory is something along the lines of:
Shape shape1 = shapeFactory.getShape("CIRCLE");
My question is: how is this any better than just using pure polymorphism without a factory, e.g.:
Shape shape1 = new Circle();
It seems to me that this achieves the common interface just like a factory. I'm not quite sure what the benefit of 'hiding the creation logic' is, when it seems like the creation logic of creating a circle is exactly the same as the creation logic of creating a factory.
The main benefit of using factories is that they offer a form of abstraction even greater than typical inheritance can offer. For example:
What does the factory do to produce the object?
Does it allocate a new object? Does it access a pool, to conserve resources? Using a factory, it's possible that the 'new' keyword is never used, saving memory and/or GC overhead. The factory can perform actions which a constructor normally shouldn't do, such as making remote proceedure calls, or accessing a database. Sometimes, the factory will return a Future instance, meaning that it could be doing the actual processing in a parallel thread!
Where does the factory come from?
Did you implement the factory yourself? Import the factory from a library? Was it injected through some form of IoC? http://en.wikipedia.org/wiki/Inversion_of_control
Is summary, factories are used because they are pretty much the ultimate form of abstraction for producing something
Yeah, that was a really bad example they gave you. The factory pattern has less to do with polymorphism, and more to do with minimizing the use of the "new" keyword.
Lets say I build a class called Manager. When I build it, it takes in a String and an int, because all it is managing is a Person object, with a name and age.
But when I grow my application, I eventually want to operate on new types of data, like adding an occupation field to my person. I want my manager to be able to take in an Enum for Occupation in its constructor along with the String and int.
Then a year later, my application has grown so much, I have subclasses of people, Data Access Objects, and all sorts of data I need to pass in to my manager. If I was not using factory, then ANYWHERE in the code where I instantiated a Manager class, I have to fix the constructor.
If instead I have used a ManagerFactory class, with a method getManager() I only need to change the constructor inside my factory class, allowing all references to getManager() to still return a Manager, no change required.
Abstract Factory design pattern is about creating families of objects, not a signle object. Eg GUI app can use different concrete factories to draw elements in different styles.
when it seems like the creation logic of creating a circle is exactly the same as the creation logic of creating a factory.
You've captured a big part of your confusion right there. In cases where creation starts getting more involved (see KeyFactory), it can simplify both your code, and the code of your consumers.
A Factory pattern is one that returns an instance of one of several possible classes depending on the data provided to it.Its a "design pattern". You can implement it even by using "polymorphism". This pattern provide a wrapper around the object creation process of "similar object".
A factory Pattern can be used to -
Reduce the complexity of the client code by hiding object creation process
Provide a common interface to expose newly created object.
When a class can’t anticipate which class of object it needs to create.
For details, you can refer http://dgmjava.blogspot.in/2011/11/factory-design-pattern.html

Is it an ok practice to have a member ClientBundle in a containing ClientBundle?

In my app, I have MyAppResources, which will mainly contain custom styles for the app. I am thinking about what is a good way to go about applying custom styles to standard widgets, such as a CellTable, along with custom styles on the layout and custom widgets?
My question:
Since MyAppResources is a singleton (it doesn't have to be, as mentioned in other posts), but CellTableResources isn't, and CellTableResources is a member of this instance that is an interface also extending ClientBundle, will a proxy 'CellTableResources' be created on every MyAppResources.INSTANCE.cellTableResources().foo()?
If so, could I create a MyAppResources.CELLTABLE_RESOURCE_INSTANCE to get around this? Or would the creation of the proxy be negligible, even if there are plentiful calls to MyAppResources.INSTANCE.cellTableResources().#?
Secondly, more of a discussion question: what is best practice in regards to using multiple ClientBundles in this case? Should I instead use CellTableResources seperately (remove it from MyAppResources), using GWT.create(CellTableResources.class); in a widget that needs it (or using a singleton like I have for MyAppResources)?
MyAppResources:
public interface MyAppResources extends ClientBundle {
public static final MyAppResources INSTANCE = GWT.create(MyAppResources.class);
#Source("MyAppStyles.css")
public MyAppCssResource css();
public CellTableResources cellTableResources();
}
CellTableResources:
public interface CellTableResources extends CellTable.Resources {
interface CellTableStyle extends CellTable.Style {
}
#Override
#Source({ CellTable.Style.DEFAULT_CSS, "CellTableStyles.css" })
CellTableStyle cellTableStyle();
#Source("green_light.png")
ImageResource getGreenLight();
//...
}
Thank you for reading.
Multi-part question, so I'm going to try to hit this in several parts:
What is the cost of GWT.create()?
Most of the GWT class is 'magic', things that you cannot wrote for yourself in other ways, as they call on the compiler to fill in specific details for you. These are often different when running in dev mode vs compiled to JS.
In the case of GWT.create, it turns out that this is compiled out to new - it is used just to create new instances. So what is the cost of a new instance versus a singleton? This depends entirely on the object being created. If there are no fields in the object, then the cost is essentially free - in fact, the compiler may choose to actually remove the constructor call, and rewrite all later methods as static anyway!
This is what happens in most cases - GWT.create should be considered to be very cheap, unless you are doing something silly like calling it within a loop that is run many times.
What happens when I list a ClientBundle method inside another ClientBundle?
Well, what happens when you list anything inside a ClientBundle?
Anything that can be listed in a ClientBundle must be annotated with #ResourceGeneratorType, indicating how to generate that type. For example, here is ImageResource:
/**
* Provides access to image resources at runtime.
*/
#DefaultExtensions(value = {".png", ".jpg", ".gif", ".bmp"})
#ResourceGeneratorType(ImageResourceGenerator.class)
public interface ImageResource extends ResourcePrototype {
//...
It calls on ImageResourceGenerator to create images as needed. Any class described in that annotation must implement com.google.gwt.resources.ext.ResourceGenerator, which describes how to get ready to work, how to create necessary fields, how to initialize them, and how to finish up.
So what does this look like for ClientBundle itself? Check out com.google.gwt.resources.rg.BundleResourceGenerator - it is a very simple class that just calls GWT.create() on the type of the method given. So, predictable, this means that those 'child' ClientBundles are created via GWT.create, more or less the same as you might otherwise do.
Okay, what does that mean in this specific case?
It turns out that ClientBundles instances don't have fields where they track newly created objects from, but instead have static members that they use instead - effectively singletons. This means that once you have called a method once, the instance it returns will be the same instance created as the next time you call it. Two different ClientBundles with the same contents will of course then keep two different copies of the objects, but it doesn't matter how many times you create a ClientBundle - its internals will always be the same.
Anything else?
Yep! Remember that you are dealing with interfaces here, not classes, so you can actually extend more than once at once!
public interface MyAppResources extends
ClientBundle,
CellTable.Resources,
CellTree.Resources {//etc
//...
Now, if two interfaces describe the same methods you may have problems, but if not, this can provide an advantage when generated sprited images. Each individual ClientBundle will draw on its own pool of images when preparing them for use - if you have a ClientBundle within a ClientBundle, they won't work together to sprite images into bigger pieces. To get that, you need to make just one ClientBundle type. This may not matter in your particular case, but I figured it was also worth mentioning.

How to call methods from other classes not having an instance?

How can I call a method from a class that is not an object within another class, and has nothing in common with this other class?
In my case:
class GridUI {
com.google.gwt.user.cellview.client.DataGrid grid;
public void refresh() {
dataGrid.redraw();
}
}
class SomeBackendService() {
public foo() {
//have to trigger refresh of a specific grid
}
}
One possibility might be to make the refresh() and grid static. But that's bad design, and I cannot use this approach as I want to use several implementations of GridUI.
So, how can I refresh a certain gridclass in my app from any service that does not contain this grid as an object??
Just create and fire an Event for it in your service and make your grid register for that Event. It's probably best to use an EventBus.
Using a static Map<String, Grid> as was suggested in the accepted answer will work but it's not proper. You risk making mistakes and it's not as easy to manage when the number of grids increases.
The EventBus approach is more work upfront but in the end it's a better approach. You'll be able to reuse the EventBus throughout your application. It really helps keep your coupling down. You'll also easily be able to get different objects act on the same Event with little effort.
Alternatively create a components registry (basically a Map<String,Grid>), then fetch the grid from SomeBackendService using its id as key in the registry. (I guess you know which grid you want to refresh, right?)
Be careful with registries though:
make sure they are thread safe if need be (probably true in an UI app)
they tend to fill up and leak memory if not properly handled
Sorry for not answering that long time, i was in vacation.
Interfaces are some kind of classes.
But they do not implement any method, they have empty method bodies.
Each class, which implements an interface usually MUST implement its methods.
In C# You would Do :
enter code here
interface IMyInterface
{
void PleaseImplementMe();
}
class clMyInterface :IMyInterface
{
void IMyInterface.PleaseImplementMe()
{
MessageBox.Show("One implementation");
}
}
end
Please let me know, whether this is what can help You or not.

Some questions about OOP in Java

I have a GUI class with a menu of buttons and textfields. Depending on what choices that is made in the menu and the input, methods in the GUI class are calling methods in the Logic class to send the input and create new objects of Customer class and Account class and so on.
To be able to communicate between the GUI- and the Logic class, I first create an object of the Logic class and I do that inside the GUI class, since it's here I have my main method. It this the best way to do it? Do I need some kind of reference variable between GUI- and Logic class or just use the reference when the object was created in the beginning of the GUI class? I guess to be able to communicate with a class, it must be an object first!? Thanks!
Logic logic = new Logic();
logic.addCustomer(name, number);
Ideally you shouldn't directly create the logic class.
You should break down the functionality into a number of small classes, each of which satisfy a responsibility.
A simplistic way would be for the GUI class to create listeners which listen to the user events. In response the to the use event they fire events that your logic registers itself for. Then when the event is received the logic class can perform the functionality.
You should read about observer pattern, event driven design...
You can read about event driven programming here http://en.wikipedia.org/wiki/Event-driven_programming .
I would instantiate the Logic class outside the GUI, but pass it as an argument to the GUI constructor. It's nearly equivalent to what you are already doing, but I think it makes it clearer that the GUI uses a Logic object. Also, it's possible that Logic does some other things before/after the GUI starts/closes; it might not be the case now, but it could be true in the future if you extend your program.
Many other answers tell you to look at MVC, but that might be overkill for your project. It can decrease complexity for a large project, but increase it for a small one.
EDIT:
Logic login = new Logic();
...
MyGUI gui = new MyGUI(logic);
...
I would suggest you do some researches on the MVC architecture. Your GUI (view) shouldn't interact directly with your model (logic). Implement a controller that will get the "signals" from your view and will be in charge to create your "logic objects" and work with them.
You can create on object of type Logic in your main and store a reference of the object in your Window object - so you can access your Logic object as long as the window exists.
You should look up the Singleton design pattern for such trivial scenarios.
By default, Java uses Reference variables. Hence, if you instantiate your object in GUI class, make sure you send the object via method calls to your processing class.
Alternatively, you can look into singleton classes, which will return only one instance of the class. Inside that class, instantiate all the objects that you will need globally, and re-use that instance throughout your program.
Generally you can. If your application is very simple.
But this approach is not scalable. As your application gets more complex it became much harder for development and support. Try to consider Model–view–controller pattern to define a best way for your design. (according to your nick name I'll take a risk to propose an alternative link)

Categories

Resources