I'm adapting Image Downloader from Google Android blog. I want ImageDownloader to be singleton since I'll be using it in multiple places in my application. I want also to be able to manipulate Bitmaps using different Strategies (eg. produce transparent bitmaps).
Context:
I want to be able to use ImageDownloader in one activity and set transparent bitmaps, and in another use the same ImageDownloader but get black&white bitmaps using different strategy object.
You think you do, but you don't want ImageDownloader to be a Singleton. Singleton is very much overused, and not appropriate in your case. Think about it: how can you manipulate Bitmaps using different strategies if there is only one instance of the class doing the manipulating?
What you want is the ability to create instances of ImageDownloader via static methods, which you can do without making it a Singleton. These methods are called Factory methods, and there are many good web pages describing them.
You probably want something like:
class ImageDownloader {
static ImageDownloader createImageDownloader(Strategy s) {...}
//...
}
Each call to the method with the same argument could return the same instance of ImageDownloader, provided the instances don't store state. Some versions of this approach are referred to as "Multiton". Google will tell you more.
I'm more inclined to agree with DJClayworth answer, but to answer your question, the best way to implement the singleton pattern is to use an enum:
public enum ImageDownloaderWrapper
{
INSTANCE;
public static final ImageDownloader IMAGE_DOWNLOADER;
private ImageDownloaderWrapper()
{
IMAGE_DOWNLOADER = new ImageDownloader();//this is where you would initialize it... looks like it has a default constructor
}
}
To get a hold of the instance:
ImageDownloaderWrapper.INSTANCE.IMAGE_DOWNLOADER.download(...
You can also take advantage of static imports:
import static some.package.structure.ImageDownloaderWrapper.INSTANCE;
Then it's a bit simpler:
INSTANCE.IMAGE_DOWNLOADER.download(...
To account for different strategies I guess you'd have to extend ImageDownloader and add the appropriate logic for dealing with strategies in that subclass (the type of IMAGE_DOWNLOADER should also correspond to the subclass you created).
You could pass a strategy as parameter to the methods responsible for the image downloading/manipulation.
Then the strategy passed will handle the manipulation. It's a fairly ugly hack though. See DJClayworth's answer for the more clean code ideas.
Related
I'm a bit confused about my new class type I've written.
My class would be used to serve question and options pulled from database for about four thousands concurrent users. (Because exam will start at the same time for all)
Now what class type should I use for making it work faster.
Would it be good if I make it static?
public static List<Questions> getQuestions(String qType){
List<Questions> objListExamsExt = new ArrayList<Questions>();
....
....
....
while (cursor.next()) {
Questions objExamQuestion = new Questions();
objExamQuestion.setQuestion_id(cursor.getString("question_id"));
....
....
....
objListExamsExt.add(objExamQuestion);
}
return objListExamsExt;
}
A case where a static class might be a good idea is when you want to collect related pieces of functionality, but you don't need to have any internal state in any object.
Normally you can create a static Utils class containing a whole bunch of related functions that are accessed outside the context of any specific object instance
A singleton allows a class for which there is just one, persistent instance across the lifetime of an application.A singleton class might be useful if you have some kind of shared resource, such as a database, an in-memory cache, or maybe some specialized piece of hardware like a robotic arm. Many parts of your program might want to use this resource and you might want to have all access to the resource go through a single point. A singleton isn't always the only way to handle these situations, but it's one of the few places I think a singleton might be a good choice.
In your case if getQuestions() is used in multiple places in your application then you can group it together inside a static Utils Class.
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
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 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.
I don't want to discuss the merits of this approach, just if it is possible. I believe the answer to be "no". But maybe someone will surprise me!
Imagine you have a core widget class. It has a method calculateHeight(), that returns a height. The height is too big - this result in buttons (say) that are too big. You can extend DefaultWidget to create your own NiceWidget, and implement your own calculateHeight() to return a nicer size.
Now a library class WindowDisplayFactory, instantiates DefaultWidget in a fairly complex method. You would like it to use your NiceWidget. The factory class's method looks something like this:
public IWidget createView(Component parent) {
DefaultWidget widget = new DefaultWidget(CONSTS.BLUE, CONSTS.SIZE_STUPIDLY);
// bunch of ifs ...
SomeOtherWidget bla = new SomeOtherWidget(widget);
SomeResultWidget result = new SomeResultWidget(parent);
SomeListener listener = new SomeListener(parent, widget, flags);
// more widget creation and voodoo here
return result;
}
That's the deal. The result has the DefaultWidget deep within a hierarchy of other objects. The question - how to get this factory method to use my own NiceWidget? Or at least get my own calculateHeight() in there. Ideally, I'd like to be able to monkey patch the DefaultWidget so that its calculateHeight did the right thing...
public class MyWindowDisplayFactory {
public IWidget createView(Component parent) {
DefaultWidget.class.setMethod("calculateHeight", myCalculateHeight);
return super.createView(parent);
}
}
Which is what I could do in Python, Ruby, etc. I've invented the name setMethod() though. The other options open to me are:
Copying and pasting the code of the createView() method into my own class that inherits from the factory class
Living with widgets that are too big
The factory class can't be changed - it is part of a core platform API. I tried reflection on the returned result to get to the widget that (eventually) got added, but it is several widget-layers down and somewhere it gets used to initialize other stuff, causing odd side effects.
Any ideas? My solution so far is the copy-paste job, but that's a cop out that requires tracking the changes in the parent factory class when upgrading to newer versions of the platform, and I'd be interested to hear other options.
Perhaps you could use Aspect Oriented Programming to trap calls to that function and return your own version instead?
Spring offers some AOP functionality but there are other libraries that do it as well.
One ugly solution would be to put your own implementation of DefaultWidget (with same FQCN) earlier on the Classpath than the normal implementation. It's a terrible hack, but every other approach that I can think of is even worse.
Just my concept idea,
It is possible that use AOP, with bytecode engineering way, to inject a aspect to the calculateHeight method.
Then, you may enable you patch by ThreadLocal or else variable.
cglib is a Java library that can do some things similar to monkey patching - it can manipulate bytecode at runtime to change certain behaviours. I'm not sure if it can do exactly what you need, but it's worth a look...
It is totally possible to monkeypatch in Java, using Unsafe.putObject and a class finder. Wrote a blog post here:
https://tersesystems.com/blog/2014/03/02/monkeypatching-java-classes/
The object-oriented way of doing this would be to create a wrapper implementing IWidget, delegating all calls to the actual widget, except calculateHeight, something like:
class MyWidget implements IWidget {
private IWidget delegate;
public MyWidget(IWidget d) {
this.delegate = d;
}
public int calculateHeight() {
// my implementation of calculate height
}
// for all other methods: {
public Object foo(Object bar) {
return delegate.foo(bar);
}
}
For this to work, you need to intercept all creations of the widget you want to replace, which probably means creating a similar wrapper for the WidgetFactory. And you must be able to configure which WidgetFactory to use.
It also depends on no client trying to cast the IWidget back to DefaultWidget...
Only suggestions I can think of:
Dig through the library API to see if there's some way of overriding the defaults and sizing. Sizing can be confusing in swing (at least to me) , setMinimum, setMaximum, setdefault, setDefaultOnThursday, ... . It's possible there's a way. If you can contact the library designer(s) you might find an answer that will alleviate the need for unpleasant hacking.
Perhaps extend the factory only overriding some default sizing parameter? depends on the factory but it might be possible.
Creating a class with the same name might be the only other option, as others have pointed out it's ugly and you're liable to forget it and break stuff when you update the api library or deploy in a different environment and forget why you had the classpath set up that way.
You can try using tools like PowerMock/Mockito. If you can mock in tests, you can mock in production too.
However these tools are not really designed to be used that way, so you'll have to prepare the environment yourself and won't be able to use the JUnit runners like you do in tests...
Well, I keep trying to post suggestions, and then I see that they won't work or that you've already mentioned you tried them.
The best solution I can think of is to subclass WindowDisplayFactory, then in the subclass's createView() method, first call super.createView(), then modify the object returned to completely throw out the widget and replace it with an instance of the subclass that does what you want. But the widget is used to initialize stuff, so you'd have to go change all of those.
Then I think of using reflection on the returned object from createView() and trying to fix things up that way, but again, that's hairy because so much stuff was initialized with the widget. I think I would try to use that approach, though, if it was simple enough to justify it over copying and pasting.
I'll be watching this, plus thinking to see if I can come up with any other ideas. Java Reflection sure is nice, but it can't beat the dynamic introspection I've seen available in languages such as Perl and Python.