I'm trying to apply a factory pattern for creating request beans to use on a protocol stack. Now the request beans hold properties with other beans - which also should be part of the factory pattern (as they are different depending on the stack).
Something like:
public interface Factory {
public Request createRequest();
}
public interface Request {
public Details getDetails();
public void setDetails(Details details);
..
}
public interface Details {
public String getSource();
public void setSource(String s);
..
}
My first attempt was to add factory methods for Details as well, but this quickly becomes a hazard - especially pass some arguments for the factory.
Also the setters become a bit weird as they actually throw a ClassCastException if you were to pass an ´Details´ implementation from another factory.
The main reason for my situation is that I'm sitting on a rather complex 3rd party request/response/stack implementation which I want to fit in under my own bean interfaces. Is there a more sensible way to do this?
You might look more into your design requirement : Which one has more different variants or implementations. Make that into a factory and leave the other. In this case it looks to me as Details can be created using a factory . (If request is not much implemented in many different ways.)
Related
I recently got a book from amazon.in named java design patterns. Now i am reading factory design pattern. I could not get what is loose coupling please help me. explain me in an easy way. give me an example.
public interface Iscan {
void scan();
}
public EyeScannerClass implements Iscan{
void scan(){
System.out.println("Some Person's eye scanned...")
}
public BarcodeScannerClass implements Iscan{
System.out.println("A produc's barcode from supermarket scanned...")
}
public ScannerFactory{
public static Iscan createScanner(){
//here you can choose which scanner to create by the help of polymorphism because different scanner classes implementing same scanner interface
}
}
public SomeBusinessLogicClass {
public void someMethod(){
//if the scanner impl changes you do not need to change your business logic. all change must be done in factory and the other users of that factory is not affected.
Iscan scanner=ScannerFactory.createScanner();
}
}
I tried to explain why it is useful using factory design pattern above. we have an interface and two implementers of that interface and a factory class which is creating scanners and a client using that factory. if sth changes at the scanner impl the client do not need to change anything. With this approach we provide loose coupling.
Consider the below code(1)
Class Vehicle{
int modelYear=2010;
Engine engine=new Engine(); //Engine object
}
Now consider this(2)
Class Vehicle{
int modelYear;
Engine engine;
Vehicle(int modelYear,Engine engine)
{
this.modelYear=modelYear;
this.engine=engine;
}
In case 1 The Vehicle class is depending on the Engine class to create Engine object means more dependency i.e tight coupling
In case 2 we are creating Engine object else where(Container) and passing the object via constructor or setter method. means less dependency i.e loose coupling.
Factory Design Pattern talks about the same thing,to decrease the dependency between 2 classes create objects elsewhere and pass them via constructors or setter methods.
Whole spring framework is based on this,i.e loose coupling where IOC container creates the objects when needed, and injects them to the respective destination(Dependency Injection)
Both Abstract Factory and Factory method patterns are creational design patterns which solves the object creation issues in different scenarios.
As per GOF Factory Method pattern
Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.
My Understanding :
Motive of the Client is to get a method present in the base Factory class get executed which is dependent upon an object whose concrete class is not known now (In such a case, either during providing the software to client, it will be defined, or it will be the client himself writing the concrete implementation, most likely in case of Framework). The not known (or likely to change) Product is provided an abstract type : IProduct, and setting a contract that in future any implementation for Product must implement this interface.
IProduct interface
package com.companyx;
public interface IProduct {
public void serve();
}
Factory class with 'a method' which needs to be executed
package com.companyx;
public abstract class Factory {
public abstract IProduct createProduct();
private void performCriticalJob(){
IProduct product = createProduct();
product.serve();
}
public void executeJob(){
//some code
performCriticalJob();
//some more code
}
}
Some concrete Product
package com.companyx;
class AppAProductFeatureX implements IProduct{
#Override
public void serve() {
//some code
}
}
Factory of the concrete Product
package com.companyx;
public class AppAFeatureXProductFactory extends Factory{
#Override
public IProduct createProduct() {
return new AppAProductFeatureX();
}
}
Client code
package com.clientcompany;
import com.companyx.AppAFeatureXProductFactory;
import com.companyx.Factory;
public class Client {
public static void main(String[] args) {
Factory fact = new AppAFeatureXProductFactory();
fact.executeJob();
}
}
As per GOF Abstract Factory pattern
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
My Understanding
The client is interested in the products, here this pattern helps in providing the product by hiding the concrete product classes behind factory classes.
Product type wanted by the client
package com.companyb;
public interface IProductA {
public void performAJob();
}
Implementation of the product
package com.companyb;
//can be named better, but lets go with this name for this time
public class ProductAVersion1 implements IProductA{
#Override
public void performAJob() {
// some code
}
}
Factory interface, (It can be also an abstract class)
package com.companyb;
public interface IFactory {
public IProductA createProduct();
}
Concrete implementation of Factory o create ProductA
package com.companyb;
public class FactoryA implements IFactory{
#Override
public IProductA createProduct() {
return new ProductAVersion1(); // concrete class of product is hidden
}
}
Client Code
package com.clientcompany.productprovider;
import com.companyb.IFactory;
import com.companyb.IProductA;
public class SomeClientClass {
private IFactory factory;
private IProductA product;
public void doSomeJobWithProductA() {
// some code
product.performAJob();
//someCode();
}
public void setFactory(IFactory factory) {
this.factory = factory;
this.product = factory.createProduct();
}
}
package com.clientcompany.productprovider;
import com.companyb.FactoryA;
public class SomeOtherClientCode {
public static void main(String[] args) {
SomeClientClass someClientClass = new SomeClientClass();
someClientClass.setFactory(new FactoryA());
someClientClass.doSomeJobWithProductA();
}
}
Q1 : Is the family of related product necessary in Abstract Factory patter , won't this pattern still be relevant if only one kind of product (like above) is there with various sub types but not various related types?
Q2 Is my understanding above correct ?
Q3 Above brings another doubt in my mind : Is Factory method more suitable for frameworks (where client can give the implementation of products) and just like template method pattern, factory invokes the createProduct() concrete implementation form the user provided Concrete Factory implementation ?
Also similarly is Abstract factory more fits for Library development, where concrete product classes (likely to vary) are hidden behind more stable Factory classes ?
I am having real difficulty in getting into your shoes. But I am quite interested in this subject so I will give a try. Involved here are concepts like library, framework, factory method, abstract factory and product family etc.
First, the library vs framework has really nothing to do with factory, abstract factory or any pattern for that matter. Library vs framework debate is not from implementational perspective where the patterns play. For example JUnit is a framework which comes with a rich assertion library. So should junit prefer one pattern over other for its internal implementation? Java itself is a framework which comes with a JCL library. Dot Net which is similar to java even calls itself a framework, and contains BCL library. So no more framework vs library debate in implementational context.
So the question boils down to which pattern should you use? It is not about the difference, which is clear, but about which one to use in which scenario. In this context, the Client Code is all code which may call the one which you are typing right now. It does not matter whether some code is written by you or someone else, in same or different jar, from same or different organization. From perspective of one code fragment, any other code (even in different method of the same class) is client code if that code has a potential to call the code which you are typing right now.
While typing any code (irrespective of framework or library status) sometimes we need to obtain instances of some object. May be we need a BufferedReader. If at compile time we are absolute sure about the concrete class of the object, KISS it and go with newing.
We may not know the concrete class of an instance. Now question aries whether the client code has this information? If the client code knows about the actual concrete class, but I do not know then we use the FactoryMethod pattern. The code I am typing will ask for an instance of a factory object in (say) its argument list. The client code knowing the actual concrete class, will supply a factory object which will do the creation. Example of this case is seen in JDBC like we want to process an sql statement. At compile time we do not know whether we should instantiate a mysql.JDBC4PreparedStatement or a microsoft.SQLServerStatement. It depends on connection string and that depends on end user. So we get hold of a Connection instance and ask it to createStatement(). See, we are delegating the construction of an object of type sql.Statement to a subclass of sql.Connection. Here the conn instance is the factory object. How we get hold of the factory is immaterial, just that we got it from client code.
If we need an instance of a Process object and at compile time we do not know whether it will be a Win32Process or a UnixProcess, we delegate the responsibility of its creation to ProcessBuilder which is builder pattern related to factory pattern. Same goes for jdbc ConnectionManager.
In case when there are many different classes not related by inheritance but by family we may use AbstractFactory. For example take jdbc's dot net counterpart DbProviderFactory. My code needs instances of Connection, Command, DataReader etc which are not related by inheritance but by family of MySql or SqlServer. So we get hold of an instance of a subclass of DbProviderFactory. May be it is a MySqlProviderFactory or a SqlProviderFactory that depends on runtime and client code. Once we have that factory, we can do CreateCommand(), CreateConnection() etc.
Hope this helps you choose between factory pattern and abstract factory pattern.
In my understanding:
A1: The family of product does not need to be necessarily related, as shown on an example diagram, only a Client is needed that has knowledge of the type of products. The relation is mostly natural as you probably don't want the same Client to create 2 unrelated objects, e.g., it would look strange if you have an "AbstractPizzaFactory" that creates Pizza and Cars, no?
A2: Technically you can provide a default factory method in the Factory pattern, so that you can still create (defaults) new Objects without always subclassing it.
A3: I would agree with you on this point, although creating a Library or a Framework is never black and white.
Abstract Factory can be seen as collection of the Factory Methods.
For better understanding examples from real life can help:
Factory Method - plasticine/mold
Abstract Factory - cards factory
From Effective Java (Item 1: Consider static factory methods instead of constructors):
The class of the object returned by a static factory method need not even exist
at the time the class containing the method is written. Such flexible static factory
methods form the basis of service provider frameworks, such as the Java Database
Connectivity API (JDBC). A service provider framework is a system in which
multiple service providers implement a service, and the system makes the implementations
available to its clients, decoupling them from the implementations.
I specifically do not understand why the book is saying that The class of the object returned by a static factory method need not even exist at the time the class containing the method is written ? Can some one explain using JDBC as the example .
Consider something like the following:
public interface MyService {
void doSomething();
}
public class MyServiceFactory {
public static MyService getService() {
try {
(MyService) Class.forName(System.getProperty("MyServiceImplemetation")).newInstance();
} catch (Throwable t) {
throw new Error(t);
}
}
}
With this code, your library doesn't need to know about the implementations of the service. Users of your library would have to set a system property containing the name of the implementation they want to use.
This is what is meant by the sentence you don't understand: the factory method will return an instance of some class (which name is stored in the system property "MyServiceImplementation"), but it has absolutely no idea what class it is. All it knows is that it implements MyService and that it must have a public, no-arg constructor (otherwise, the factory above will throw an Error).
the system makes the implementations available to its clients, decoupling them from the implementations
Just to put it in simpler way you don't add any dependencies of these JDBC vendors at compile time. Clients can add their own at runtime
I have 3 objects, a DTO called BalanceDTO which implements a interface RequestDTO and a Balance Entity. I created the DTO because the entity I can't use, JAXB compliance (legacy code).
The DTO is used in the web service layer, BalanceService, and the Entity in the API I integrate to from the web service. Between the web service and the API there is validation. RequestValidation which has sub validations for each type of RequestDTO i.e. BalanceRequestValidation.
The validation component takes in a RequestDTO as a parameter and then needs to do validation for the specific component. At the point of input the validation component doesn't know which object has been passed to it i.e. BalanceDTO, it only sees the interface.
I want to avoid using instanceof so I was thinking of using a visitor on the DTO so that it delegates itself to the validation that needs to be performed on it.
But the validation needs more/other components as well not just the BalanceDTO as input parameters and different validations needs different input params.
Is there another way to know which object you are working with and the validation to choose without using instanceof? Another design that I can follow?
You are well on the right track here - the Visitor design pattern is often the best way to avoid downcasting.
I am going to suggest a combination of the visitor and delegation design patterns, though let's walk through some alternatives.
Having the object do the validation itself via the RequestDTO interface is not viable since you need different components and the validation is not trivial in nature.
Using instanceof and downcasting looks a little messy, and the compiler won't complain if you add a new validatable class and forget to add the validator - you'll be relying on a runtime error via ...else { throw new IllegalArgumentException("Unknown RequestDTO subtype!"); }
The visitor design pattern is the classic way to avoid downcasting plus it also gives you a compiler error if you add a new class that should be validatable and forget to add the validation.
You can use accept() and visit() methods, or you can use method naming that is closer to your domain, e.g. validate(), like this:
public interface RequestDTO {
boolean validate(RequestValidation validator);
}
public class BalanceDTO implements RequestDTO {
// ...
#Override
public boolean validate(RequestValidation validator) {
return validator.validate(this);
}
}
public class RequestValidation {
// components...
public boolean validate(BalanceDTO balanceDTO) {
return true; // todo...
}
public boolean validate(AnotherDTO anotherDTO) {
return true; // todo...
}
}
If you want to go a bit further you can delegate the validation to specific validation components, like this:
public class RequestValidation {
BalanceRequestValidation balanceRequestValidation;
AnotherRequestValidation anotherRequestValidation;
public boolean validate(BalanceDTO balanceDTO) {
return balanceRequestValidation.validate(balanceDTO, a, b, c);
}
public boolean validate(AnotherDTO anotherDTO) {
return anotherRequestValidation.validate(anotherDTO, x, y, z);
}
}
Given I have understood your problem correctly, the visitor design pattern, possibly combined with the delegation design pattern, is indeed a good approach.
I better explain the question with an example.
I have an Interface Model which can be used to access data.
There can be different implementations of Model which can represent the data in various format say XMl , txt format etc. Model is not concerned with the formats.
Lets say one such implementation is myxmlModel.
Now i want to force myxmlModel and every other implementation of Model to follow Singleton Pattern.The usual way is to make myxmlModels constructor private and provide a static factory method to return an instance of myModel class.But the problem is interface cannot have static method definitions and a result i cannot enforce a particular Factory method definition on all implementation of Model. So one implementation may end with providing getObject() and other may have getNewModel()..
One work around is to allow package access to myxmlModel's constructor and create a Factory class which creates the myxmlModel object and cache it for further use.
I was wondering if there is a better way to achieve the same functionality .
Make a factory that returns
instances of your interface, Model.
Make all concrete implementations of the model package-private classes
in the same package as your factory.
If your model is to be a singleton, and you are using java
5+, use enum instead of traditional
singleton, as it is safer.
public enum MyXMLModel{
INSTANCE();
//rest of class
};
EDIT:
Another possibility is to create delegate classes that do all the work and then use an enum to provide all of the Model Options.
for instance:
class MyXMLModelDelegate implements Model {
public void foo() { /*does foo*/}
...
}
class MyJSONModelDelegate implements Model {
public void foo() { /*does foo*/ }
...
}
public enum Models {
XML(new MyXMLModelDelgate()),
JSON(new MyJSONModelDelegate());
private Model delegate;
public Models(Model delegate) { this.delegate=delegate; }
public void foo() { delegate.foo(); }
}
You can use reflection. Something like this:
public interface Model {
class Singleton {
public static Model instance(Class<? extends Model> modelClass) {
try {
return (Model)modelClass.getField("instance").get(null);
} catch (blah-blah) {
blah-blah
}
}
}
public class XmlModel implements Model {
private static final Model instance = new XmlModel();
private XmlModel() {
}
}
usage:
Model.Singleton.instance(XmlModel.class)
Actually, I don't like this code much :). First, it uses reflection - very slow, second - there are possibilities of runtime errors in case of wrong definitions of classes.
Can you refactor the interface to be an abstract class? This will allow you to force a particular factory method down to all implementing classes.
I used to ask myself the same question. And I proposed the same answer ;-)
Now I normally drop the "forcing" behavior, I rely on documentation.
I found no case where the Singleton aspect was so compelling that it needed to be enforced by all means.
It is just a "best-practice" for the project.
I usually use Spring to instanciate such an object,
and it is the Spring configuration that makes it a Singleton.
Safe, and so easy ... plus additionnal Spring advantages (such as Proxying, substituing a different object once to make some tests etc...)
This is more an answer to your comment/clarification to kts's answer. Is it so, that the real problem is not using the Singleton pattern but instead defining an eclipse (equinox) extension point schema that allows contributing a singleton?
I think, this can't be done, because everytime you call IConfigurationElement.createExecutableExtension you create a new instance. This is quite incompatible with your singleton requirement. And therefore you need the public default constructor so that everybody can create instances.
Unless you can change the extension point definition so that plugins contribute a ModelFactory rather than a model, like
public interface ModelFactory {
public Model getModelInstance();
}
So the extension user will instantiate a ModelFactory and use it to obtain the singleton.
If I guessed wrong, leave a comment and I delete the answer ;)