Suppose I have a class called Factory. I intend to have that class publicly accessible so anyone can create and access the factory. I want the factory to create and distribute widgets. I only want the factory to be able to create widgets, not anyone in the public program space. However, I'd like to have a method called distribute() that would give out a widget to the main program. At that point the main program could access all the public methods of that widget. It could also give it back to the factory if need be, thereby removing any public access to that object.
If this is possible, how does one accomplish this?
What you're looking for is an inner class. By declaring the constructor of the inner class private, only the encapsulating class can access it! Then you create a factory method in the outer class to build the widget and distribute it. I've declared it static here, but that's not necessary, depending on your needs.
public class Factory {
public static Widget buildWidget() {
Widget widget = new Widget();
return widget;
}
public class Widget {
private Widget() { ... }
public void someMethod() { ... }
}
}
Note that in clean code your other concerns must be addressed by being careful about your referential integrity. To 'give back' the widget all other references to it must be released. Your Factory can certainly keep track of what widgets it's given out, but it's very hard to 'recall' widgets reliably.
You're describing access control that changes over time ("It could also give it back to the factory if need be, therby removing any public access to that object."). Java doesn't work that way. All of the access qualifiers are statically checked, and remain constant for the entire lifetime of the program.
Place the widgets in the same package as the factory, and set the widget's constructors to have protected visibility. This will restrict the creation of objects to the factory.
For each widget, the access control can be partially implemented. You can keep a List in each of the widgets of Objects that are allowed to access, and only the factory can modify this list (protected visibility). For all public functions, you require the user to pass in an object that has been authorized to access the functions of the widget. You can return the object by passing the object that is authorized back to the factory so that it will remove the authorization.
You can pass a private object in the main class as authorization object - this will prevent other classes from using the widget. However, this doesn't prevent other classes from asking for authorization, though.
This is a bit flaky, since you may forgot to release the authorization and clutter the widget with "undead object" (not used anywhere else except for the access control list in the widget).
Related
I have tried doing a search for this but I fear I may not be wording what I want to do very well.
Currently, we have about a hundred action classes in our application with each determining if a user has access to it. I would like to make a class that can figure out the calling method, what permissions are required for it, and if the user has those permissions. Unfortunately, I don't really know how to even get started with this as each class may have slightly different requirements.
I'm happy to add more explanation if needed but as I said, I'm not sure I'm wording what I'm trying to do very well so if anyone has a better way of putting it that gets me some google results or a link to a related question here that's already been answered, I know I'd appreciate it.
current permissions checks look like below. This is a simple implementation, there are usually multiple profile checks in one if block.
If (scc.getUser().getCurrentProfile().getSystemAdmin() != 1) {
logIllegalAccess(log);
break;
}
IMHO the most elegant solution would make use of annotation processing. The idea is that you would annotate action classes with a custom annotation, something like:
#RequiredPermission(Permissions.SYSADM)
class ActionA {
public ActionA newInstance() {
return new ActionA_Gen(new ActionA());
}
private ActionA() {...}
...
}
Action classes would have to have a newInstance() method to be used to create instances instead of calling new. The method would create an instance of a class by the same name with _Gen extension. This class would have one method for each method in the original action class, which would perform a permission check and call the corresponding method in the original class instance that was passed to its constructor.
The _Gen class would be generated by an annotation processor.
Note that by using reflection it might be possible to move the newInstance() method in a common superclass.
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'.
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.
My current application has a JFrame with about 15 actions stored as fields within the JFrame. Each of the actions is an anonymous class and some of them are pretty long.
Is it common to break actions into their own classes possibly within a sub-package called actions?
If not, how's this complexity usually tamed?
Thanks
If it is possible that your actions could be reusable (e.g., from keyboard shortcuts, other menus, other dialogs, etc.) and especially if they can work directly on the underlying model (rather than on the UI), then it is generally better not to have them as anonymous classes.
Rather, create a separate package, and create classes for each.
Often, it also makes sense to not instantiate these directly but rather have some sort of a manager that defines constants and initializes and returns sets of actions, so that you could, for example, offer different action sets at different versions or set certain actions only for internal releases.
Finally, check whether your actions can be refactored into a class hierarchy. They often can, which saves code replication, and also helps you add robustness (e.g., check for certain conditions before letting the action execute).
That's typically how I do it. Each action gets it's own class which has a reference to the "app" object so it can get to resources it needs. I usually have an action manager that holds all the actions so there's one place to access them as well as one place to update their enablement and stuff.
Eventually this also becomes unmanageable at which point you should start thinking about using an app framework like Eclipse RCP, the NetBeans framework, JIDE, etc. This is especially true if you want to support user-defined keymaps and stuff like that.
What I do is create a package (package tree actually) for action classes, then instantiate each class according to context. Almost all of my action classes are abstract with abstract methods to get the context (ala Spring).
public abstract class CalcAndShowAction extends AbstractAction {
//initialization code - setup icons, label, key shortcuts but not context.
public void actionPerformed(ActionEvent e) {
//abstract method since it needs ui context
String data = getDataToCalc();
//the actual action - implemented in this class,
// along with any user interaction inherent to this action
String result = calc(data);
//abstract method since it needs ui context
putResultInUI(result);
}
//abstract methods, static helpers, etc...
}
//actual usage
//...
button.setAction(new CalcAndShowAction() {
String getDataToCalc() {
return textField.getText();
}
void putResultInUI(String result) {
textField.setText(result);
}
});
//...
(sorry for any mistakes, I've written it by hand in this text box, not in an IDE).