I am new with design pattern, and I don't know which I have to apply in this case.
I have some data in a file, so I have to model that data and then start a class with that data.
For the reading of the file and the modeling I choose to apply the Dao pattern, so there is interface (Interface) and his implementation (InterfaceImplementation) that read the file and return the model data (DataModel).
After I have to instantiate another class (Runner) with that model data e call one of its method.
This is what I have done:
public class Factory {
public void start() {
Interface dao = new InterfaceImplementation();
DataModel data = dao.getDataModel();
Runner runner = new Runner(data);
runner.run();
}
}
So the client call only the method new Factory().start().
I have some doubts about this solution, I don't think this is a good solution and a good applying of the Factory pattern.
I hope to have been clean, cheers.
Your Factory class is actually not an implementation of the Factory creational pattern. It is an implementation of the Facade pattern.
Your Factory class's purpose is not only to simplify the instantiation process of a Runner, but to simplify the entire process of starting a Runner which makes it more than a factory.
On a side note, naming things is one of the most important aspect in programming. Choose meaningful names of the Ubiquitous Language of your domain.
public class Factory {
public void start() {
Interface dao = new InterfaceImplementation();
DataModel data = dao.getDataModel();
Runner runner = new Runner(data);
runner.run();
}
}
2 remarks :
A factory creates an object and generally provides a instance of that. Which looks like more to a factory in your code is :
DataModel data = dao.getDataModel();
Why re-instantiate InterfaceImplementation at each start() call ?
If you have multiple DataModels, a useful factory could by example create/retrieve a specific DataModel for clients.
public class DataModelFactory {
private Interface dao = new InterfaceImplementation();
public DataModel GetDataModelXXX() {
DataModel dataModel = dao.getDataModelXXX();
return dataModel ;
}
public DataModel GetDataModelYYY() {
DataModel dataModel = dao.getDataModelYYY();
return dataModel ;
}
}
A factory is intented to ease the creation of an object. In a factory after the creation the object will be returned.
So create the Runner and give it back to the caller.
There you can decide next what to do with it.
Its also important to give the method meaningful names.
The thing that caught my attention: in your current implementation, your client is "kinda" completely decoupled from all other activities. But not in a positive way.
Your client code calls start(); and then internally, a lot of things happen. But there is not even a return value from that method.
I am wondering now: how would any of this have an "lasting" effect on your system? Are there some implicit side effects; like that Runner updating some global state singleton somewhere?
In other words: given your code, what would happen if start() is called multiple times?! Or ... zero times?!
In that sense, it is not at all clear to me how this code "relates" to anything else. And well, that looks like a problem to me that you should look into.
( and yes, I understand that my input is more of a "code/design review" than a real answer; but heck, maybe it can be helpful )
Related
I'm trying to develop a simple application using OSGi framework. My question involves an "utility bundle" available in the framework: let me explain with a pretty verbose example. At the moment I'm trying to build an event my bundle will send.
From what I understood, what i need is to do something like the following (event admin felix):
public void reportGenerated(Report report, BundleContext context)
{
ServiceReference ref = context.getServiceReference(EventAdmin.class.getName());
if (ref != null)
{
EventAdmin eventAdmin = (EventAdmin) context.getService(ref);
Dictionary properties = new Hashtable();
properties.put("title", report.getTitle());
properties.put("path" , report.getAbsolutePath());
properties.put("time", System.currentTimeMillis());
Event reportGeneratedEvent = new Event("com/acme/reportgenerator/GENERATED", properties);
eventAdmin.sendEvent(reportGeneratedEvent);
}
}
Now, since an OSGi application may have lots of bundles, I thought to create a subclass of Event for every bundle (eg. I have a bundle named "BundleExample"? Inside it's exported classes there will be a "BundleExampleEvent"). I know this doesn't add any information since you can know which event you received by looking at "topic", but please bear with me for the moment.
Now, the Event constructor needs a topic and a Map<String, Object>. However, to "simplify" the event constructor, I would like to have only the topic and the list of parameters to put inside the map. For example here's what might be a BundleExampleEvent class:
public class BundleExampleEvent extends Event{
private int importantVariable;
public BundleExampleEvent(String topic, int importantVariable) {
super(topic, Utils.toMap("importantVariable", importantVariable));
//here toMap is static
}
public int getImportantVariable() {
return this.importantVariable;
}
}
Ok, please note the Utils.toMap: it's a function that allows you to convert a sequence of String, Object into a Map. Ok, now Utils is an example of a utility class (stupid, useless but a utility class nonetheless). In the spirit of OSGi I want to make this utility class a bundle as well: my thought would be to start this Utils bundle at framework boot and then whenever I need one of its utility I want to fetch a reference via #Reference annotation.
This can work greatly in any bundle interface implementation, like this:
#Component
public class BundleExampleImpl implements BundleExample {
#Reference
private Utils utils;
#Override
public String sayHello() {
return this.utils.fetchHello();
//another useless utility function, but hopefully it conveys what i'm trying to do
}
}
But what about other classes (i.e. called by BundleExampleImpl during its work)? For example what about the BundleExampleEvent? I need to call it from sayHello method and I want to use this utility also inside that class in order to compute the Map! In the previous example i used a static function, but I would like to use the reference of Utils OSGi gave me.
Of course I could add a parameter inside the constructor of BundleExampleEvent in order to satisfy the link but I rather not to do it because it's pretty silly that something would depend on an "utility class"; my question are:
Is this the only method available if I want a "utility bundle"?
Or can I do something weird like adding a reference of Utils also in my BundleExampleEvent; i.e. something like this:
public class BundleExampleEvent extends Event{
#Reference
private Utils utils;
private int importantVariable;
public BundleExampleEvent(String topic, int importantVariable) {
super(topic, Utils.toMap("importantVariable", importantVariable));
//here toMap is static
}
public int getImportantVariable() {
return this.importantVariable;
}
}
Or maybe the whole idea of having an "utility bundle" is just pure trash?
Thanks for any reply. Hope I could convey my problem in the clearest way
I don't think there is any point in Utils being a service. Things should only be a service if they can conceivably have multiple implementations. In your case, the consumer of the Util functionality only ever wants a single implementation... the implementation is the contract.
I don't even think the utils code should be in a bundle. Just make it into a library that is statically linked into the bundles that need it.
In your case the Utils utils would be an OSGi service. Then you want to use this service inside an object that is not a service like BundleExampleEvent.
What you could do is to create a service that creates BundleExampleEvent instances and feeds it with an OSGi service. Kind of like a factory as a service. The problem with this is that services in OSGi are dynamic. If the service needed by the BundleExampleEvent instance goes away then the object would have to be discarded. So this only works for short lived objects.
In the eventadmin example a different solution would be to not use a special event class but instead create a service that has a method to send such an event. Then all the magic would happen inside this method and the result would be an event without further logic. You could also inject EventAdmin into that service using DS.
This works very well in OSGI but has the disadvantage of the anemic domain model (http://www.martinfowler.com/bliki/AnemicDomainModel.html).
I am not sure which variant to prefer.
I have recently started working on a Java project that is already with a sizeable codebase developed by a team over 3 months. I noticed that at many places , some objects they are instantiating directly in the constructor of the client object , rather than using a dependency injection. I wanted to refactor the object construction into a factory and use some injection framework.
I have created a factory that essentially is a one liner for a doing new <type(some params here)>. There is nothing fancy here - no singleton , no static factory pattern. Just a newInstance() method that returns a new instance of the dependency.
To show something in code :
class A { A() {
B bobj = new B(); // A and B are coupled directly
}
}
I want to refactor this to :
BFactory {
newInstance() { return new B(); // return B implementation }
}
class A {
A(BFactory factory){
B bobj = factory.newInstance(); // A does not know about B impl
}
}
My argument is that objects should not be created anywhere in the code except in a Factory meant for that purpose. This promotes loose coupling , otherwise you are coupling the two types tightly. One senior member ( the author of the code I am trying to refactor ) feels that the one liner factory is a over-complicating design.
Are there authoritative advices/references on patterns governing this problem ? Something that can be used to decide which approach is better and why exactly ?
One senior member ( the author of the code I am trying to refactor ) feels that the one liner factory is a over-complicating design.
This looks like the crux of your question and not whether you should be refactoring the code or not so let us answer it rather than deviating from the actual question. If we consider the examples that you present in your code, I agree with your colleague. You shouldn't be creating a factory class for each dependency you want to inject. There is nothing wrong with what you are trying to achieve but the way you try to achieve it is an overkill.
You either depend upon a hierarchy of Factory classes that know how to create each and every dependency or you depend on the actual class itself and have a Container that can wire the objects together for you.
Option 1 : Depend on a common Factory
class A {
B bobj;
C cobj;
A(Factory factory){
bobj = factory.createB();
cobj = factory.createC();
}
}
Option 2 : Depend on the dependency directly
class A {
B bobj;
C cobj;
A(A a,B b) {
this.bobj = b;
this.cobj = c
}
}
You can then create a Container class that knows how to wire objects together :
class Container {
public static B createB() {
return new BImpl();
}
public static C createC() {
return new CImpl();
}
public static A createA() {
return newAImpl(createB(),createC());
}
}
The examples presented above are way too basic. In the real world, you will mostly have a more complex graph of dependencies. That's where DI frameworks come in handy instead of reinventing the wheel. If your ultimate goal is to start using a DI framework, you could go with option 2 since DI frameworks achieve inversion of control by supplying dependencies to their clients rather than the client code asking for them.
Your underlying point is perfectly valid, it's usually not a good idea to instantiate objects directly in the constructor (they may be valid exceptions from that rule).
If you do this:
class Car {
private Engine engine;
public Car() {
engine = new Engine();
}
}
You will have a hard time testing the Car without the engine. You'll have to use reflection in order to exchange the instance by a mock.
If you do the following instead
class Car {
private Engine engine;
#Inject
public Car(Engine engine) {
this.engine = engine;
}
}
it is very easy to test the Car with a fake engine, replace the implementation of engine or change the way the engine should be constructed (e.g. add more parameters to the constructor).
But you should definitely use an established dependency injection framework instead of writing your own factories. If you pass in a "common factory" as Chetan suggested you end up hiding your dependencies.
Good resources for more motivation using dependency injection can be found here:
https://github.com/google/guice/wiki/Motivation or
https://youtu.be/acjvKJiOvXw (very good talk, should be worth your time).
In the project I'm working on (not my project, just working on it), there are many structures like this:
project.priv.logic.MyServiceImpl.java
project.priv.service.MyServiceFactoryImpl.java
project.pub.logic.MyServiceIF.java
project.pub.service.MyServiceFactoryIF.java
project.pub.service.MyServiceFactorySupplier.java
And the Service is called like this:
MyServiceFactorySupplier.getMyServiceFactory().getMyService()
I understand that a factory is used to hide the implementation of MyServiceImpl if the location or content of MyServiceImpl changes. But why is there another factory for my factory (the supplier)? I think the probability of my Factory and my FactorySupplier to change is roughly equal. Additionally I have not found one case, where the created factory is created dynamically (I think this would be the case in the Abstract Factory Pattern) but only returns MyServiceFactoryImpl.getInstance(). Is it common practice to implement a FactorySupplier? What are the benefits?
I can think of a couple of examples (some of the quite contrived) where this pattern may be useful. Generally, you have two or more implementations for your Services e.g.
one for production use / one for testing
one implementation for services accessing a database, another one for accessing a file base storage
different implementations for different locales (translations, formatting of dates and numbers etc)
one implementation for each type of database you want to access
In each of these examples, an initialization for your FactorySupplier is needed at startup of the application, e.g. the FactorySupplier is parametrized with the locale or the database type and produces the respective factories based in these parameters.
If I understand you correctly, you don't have any kind of this code in your application, and the FactorySupplier always returns the same kind of factory.
Maybe this was done to program for extensibility that was not needed yet, but IMHO this looks rather like guessing what the application might need at some time in the future than like a conscious architecture choice.
Suppose you have a hierarchy of classes implementing MyServiceIF.
Suppose you have a matching hierarchy of factory classes to create each of the instances in the original hierarchy.
In that case, MyServiceFactorySupplier could have a registry of available factories, and you might have a call to getMyServiceFactory(parameter), where the parameter determines which factory will be instantiated (and therefore an instance of which class would be created by the factory).
I don't know if that's the use case in your project, but it's a valid use case.
Here's a code sample of what I mean :
public class MyServiceImpl implements MyServiceIF
{
....
}
public class MyServiceImpl2 implements MyServiceIF
{
....
}
public class MyServiceFactoryImpl implements MyServiceFactoryIF
{
....
public MyServiceIF getMyService ()
{
return new MyServiceImpl ();
}
....
}
public class MyServiceFactoryImpl2 implements MyServiceFactoryIF
{
....
public MyServiceIF getMyService ()
{
return new MyServiceImpl2 ();
}
....
}
public class MyServiceFactorySupplier
{
....
public static MyServiceFactoryIF getMyServiceFactory()
{
return new MyServiceFactoryImpl (); // default factory
}
public static MyServiceFactoryIF getMyServiceFactory(String type)
{
Class serviceClass = _registry.get(type);
if (serviceClass != null) {
return serviceClass.newInstance ();
} else {
return getMyServiceFactory(); // default factory
}
}
....
}
I have a related hierarchy of classes that are instantiated by a hierarchy of factories. While I don't have a FactorySupplier class, I have in the base class of the factories hierarchy a static method BaseFactory.getInstance(parameter), which returns a factory instance that depends on the passed parameter.
I'm learning Java and want to implement method chaining to build a set of execution instructions. I've heard about some design patterns like builder or command pattern (I don't know what those patterns are btw, just heard their names floating around in my learning journey). But not sure if I would be complicating things if I chose to go with a OOP design pattern.
So this is what I want to build:
Hypothetically speaking, lets say I have a class in my program called DatabaseOperator.
In terms of design, I would I go about designing the class so that the client that uses DatabaseOperator could use it like shown below:
public static void main(String args[]){
DatabaseOperator do = new DatabaseOperator();
DatabaseOperator.getConfigurations("fileName").getAuthenticationDetails("somefile").
joinCluster("clusterName").launchMode("TEST").initiateConnection();
}
How should I design my DatabaseOperator class? Any particular design pattern I can use or is it not needed?
Thank you in advance.
You could design your DatabaseOperator class to support chained invocations, by returning the this object in the different methods. Each of these methods will update the state of the DatabaseOperator in order to facilitate proper execution of other methods (such as initiateConnection()) down the line.
As Jordao pointed out, this looks more like a Fluent Interface (that uses a Builder pattern under the hood). One possible implementation could be:
public class DatabaseOperator {
private Configuration configuration = Configuration.DEFAULT;
private AuthDetails authDetails = AuthDetails.DEFAULT;
public DatabaseOperator withConfigurationsFrom(String fileName) {
//Get the configurations from the file, and initialize the 'Configuration' object
configuration = initializeFrom(fileName);
return this;
}
public DatabaseOperator withAuthenticationDetailsFrom(String fileName) {
// Get authentication details from the file, and initialize AuthenticationDetails
authDetails = initializeAuthDetailsFrom(fileName);
return this;
}
//.. and so on
public void initiateConnection() {
//Uses configuration and authDetails
}
}
I have long used reflection to decouple modules from "handlers".
I have a code base which is architected like this :
static enum AnimalHandlers {
Dog(Dog.class),
Cat(Cat.class);
private final Class c;
AnimalHandlers(Class class)
{
this.c=class;
}
public Class getAnimalHandler()
{
return c;
}
}
Then later in my code, I have a method which takes an "Animal" enum as input and uses reflection (that is, it gets the class from the enum and invokes "newInstance") to invoke the necessary handler.
I think the solution would be cleaner with Guice. How can I get rid of the enum/reflection and simply use guice to "hydrate" my control module with domain specific logic handlers?
You could well use a MapBinder<AnimalEnum, AnimalHandler>, and define a binding for each possible AnimalEnum value.
I think that there must be a better pattern here. I'm a little confused as to just how the Animal enum interfaces with the handler but I'll make some general suggestions and maybe one will stick.
I assume that there is no way to define the handlers in the Animal enum and you want to decouple the classes. Fine.
Could the the handlers register themselves with Animal.setHandler(...)? Then you could just call Animal.Dog.getHandler() to get Dog's handler.
I agree with #jfpoilpret that some sort of AnimalHandlerMapper would also be better. I assume there a common interface is possible, even if it just a marker interface.
Code:
private static Map<Animal, AnimalHandler> handlerMap
= new HashMap<Animal, AnimalHandler>();
static {
Dog dog = new Dog();
handlerMap.put(Animal.Dog, dog);
// we use the same handler twice here
handlerMap.put(Animal.Wolf, dog);
handlerMap.put(Animal.Cat, new Cat());
// do a Animal.values loop at the end to verify that everyone has a handler
}
public static AnimalHandler getHandler(Animal animal) {
return handlerMap.get(animal);
}
If for some reason you can't use the handler instances then I would do the same thing but with handler factories. So you've call handlerMap.get(animal).create(animal) or some such. This would be much cleaner than using reflection.
I'm not sure how Guice compares to Spring but if this was spring I would instantiate the handler beans and they would register with the AnimalHandlerMapper to completely decouple it.
Hope this helps.