Benefit of factory class over other polymorphism - java

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

Related

Starting method in all implemented classes

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();
}
}

Spring Singleton means no data sharing at class level?

I am confused.
Spring's default bean scope is Singleton. That means that once you define a bean of your class, every time a new "message" comes in, it will be processed by the same instance of that class.
But that also means that you cannot have mutable instance variables in that singleton bean because the next call of a method of that class will see data from past calls..
Example:
Calculator is my bean (singleton)
public class Calculator {
private List<String> operations = new ArrayList<String>();
public void calculate(String op, double val) {
operations.add(op);
// do some calculations
}
public List<String> getAllOperations() {
return operations;
}
}
Here's the client (useCalc is invoked many times!):
public class CalculatorClient{
#Autowired
private Calculator calculator;
public void useCalc () {
calculator.calculate("Add",100);
calculator.calculate("Div",100);
calculator.calculate("Diff",100);
List<String> allOperations = calculator.getAllOperations();
// Do something..
}
}
So let's say CalculatorClient useCalc gets called several times with different operations..
eventually operations in Calculator will contain all of the operations ever done on that calculator.
So the question is this:
Is this Spring's limitation - not being able to effectively share information between methods within a class? And if it is so, how to share that kind of information between methods?
I know there is the prototype bean scope. Is that the only solution in this case?
BTW, prototype is not a solution here because with prototype a new class will get instantiated with every call to calculator:
calculator.calculate("Add",100); // New
calculator.calculate("Div",100); // New
calculator.calculate("Diff",100); // New
And since Singleton is the default scope - aren't developers inadvertently introduce such bugs?
A common use case for singleton beans are to inject services into other objects.
Example, to provide an object a service to connect to the database, you "autowire" a database connection bean.
You don't want to create a new instance of the database every time, so singleton beans make sense.
Usually, the object itself that uses the autowire is a singleton as well (in a web app, the Controllers are also created just once, you don't want to create a controller for every request).
aren't developers inadvertently introduce such bugs?
Since the idea is to process several requests concurrently, all of those objects are usually already coded without having common state shared using instance variables.
This is not a "limitation", but rather a default for the most common use case.
I know there is the prototype bean scope. Is that the only solution in this case?
It sounds like a good "solution" to this, in that case a new bean will be created. Note that it would not make sense to autowire a prototype bean into a singleton since in that case there will only be once instance anyway.
Another possibility more commonly used is autowiring a singleton bean that acts like a factory, then ask that factory for a new object each time you need one.
The factory can be a singleton since you don't want more than one factory, but it would then return new objects in every call to its "create" method.
So in your example, you could do something like
#Autowired
private CalculatorFactory calcFactory;
public void useCalc () {
calculator = calcFactory.createCalculator();
calculator.calculate("Add",100);
calculator.calculate("Div",100);
calculator.calculate("Diff",100);
List<String> allOperations = calculator.getAllOperations();
// Do something..
}
}
There's a lot of conflation going on here. Let me try to unravel the premises.
The whole point of dependency injection is to make it so that you don't have multiple instances of a critical application service, which would lead to things getting out of sync or result in erratic behavior (e.g. multiple database connections, multiple access points to a JMS queue, multiple ways to query a database, etc).
It is not a mandate to make everything injectable.
If something is not inherently reusable, or you would not gain anything from registering it in the component scan, then there is no reason to make that thing either a bean or a component.
It is fairly reasonable to assume that beans shouldn't store state, but that doesn't mean that something else couldn't store that state on its behalf. For instance, you could put those operations into some other backing store as opposed to in-memory, and you'd still be able to keep the state of operations you've done.
The big thing that I'm seeing is that you've kind of implemented your Calculator class half-thinking that it was a bean, and half-thinking that it was newed up somewhere. By having that list in your class, you're subconsciously forcing yourself to hold onto the state in any instance created, which violated the inversion of control principle - you don't control the lifecycle of the object.
To get around this...you have a few options available.
Change how you're storing the state of your operations. Put it into a SQLite database or a file or somewhere that isn't dependent on an instance maintaining it.
Inject your own. You can create a bean that is of type List<String>, and require your Calculator to inject it when it's needed.
Don't create a bean. You can new this and Spring isn't really going to fuss at you. It'd make it harder to test, though.
The first two approaches abstract away the notion of storing the data from an operation and reading the data from the operations. You can either read from the injected operations bean or from the SQLite database or from the flat file to get the result of operations that you want.

Why would a framework implement factory methods to create simple primitive objects?

I'm working with a Java framework that uses factory methods to instantiate simple objects. For example they have their own Double object that you must instantiate using syntax like Double.make(). I'm not too familiar with factories but aren't they supposed to be used with more complex objects? Why have a factory method that's going to make me the same object every time? Am I missing something here?
One reason I can think of to use factory method pattern in this scenario is to be able to control the object creation for class Double. I.e. it may return a new Double object everytime a call is made by invoking api Double.make() or it can choose to reuse an existing object and return that (even like a singleton pattern). Essentially this way you keep the control of object generation in the Double class and clients of that class don't need to know how the object is getting created that they are using.
You can use a factory method regardless of the complexity of the object, as you are finding here. Without seeing any code or even knowing what framework you are using, or what project you are working on, I can't deduce why the original designer did what they did. But assuming you must use the framework, then getting used to it should be your best course I guess.

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.

Java best practice library creation for flexible class creation (Factory Pattern, abstraction, and interfaces)

Imagine I am a Java software developer for a car manufacturer. I have been tasked with creating a library that will be used by numerous in-house applications. For each type of car model manufactured, I create a java object representing that model. I must be able to track not only current models, but prototype models. The prototype models will have one name that is very likely to change once it goes into production. I need to be able to use the library to account for the prototypes and flex with the name change when they are switched into production.
My question is, what is the best approach for this?
Here are my thoughts...
I have been reading several books for ideas as to best handle this situation. Immediately my mind jumps to using a factory pattern. I would have a CarModelFactory class which would return a concrete object for each model. For example:
public class CarModelFactory() {
public CarModel createCivicModel() {}
public CarModel createAccordModel() {}
public CarModel createPrototype1() {
return new ModelX();
}
public CarModel createPrototype1() {
return new ModelY();
}
Would this be the best approach? I feel like there should be another layer of abstraction. Problems I see are:
1) What if ModelX goes into production, I create a method for it and put something else in createPrototype1 method, now programs that call that method get the wrong object
2) How do I handle ModelX changing its name?
I thank you for your time!
The factory model sounds good, but I would suggest a createCarModel(String model) method, which looks up in a map the appropriate object. Then renaming a car model is a simple add/remove in that map. With appropriate synchronization, of course, to prevent a rename and a get from colliding.
The map would likely be Map<String, Class<? extends CarModel>>, and the createCar method would instantiate the class using a no-argument constructor, which you would require of all Cars.
This way, there is no recompile necessary any time you add or rename a model, as the factory class does not change its set of method signatures.
Additionally, if you override the ClassLoader, you can unload an old model and load up a new model, allowing the actual directory containing your .class files to be kept clean (no old prototype classes that have since been made into real models).

Categories

Resources